PatchworkOS
Loading...
Searching...
No Matches
atan.c
Go to the documentation of this file.
1#include <math.h>
2#include <stdbool.h>
3
4// https://en.cppreference.com/w/c/numeric/math/atan.html
5double atan(double x)
6{
7 if (x == 0.0 || x == -0.0)
8 {
9 return x;
10 }
11
12 if (isinf(x))
13 {
14 return (x > 0.0) ? M_PI_2 : -M_PI_2;
15 }
16
17 if (isnan(x))
18 {
19 return NAN;
20 }
21
22 bool negate = 0;
23 if (x < 0.0)
24 {
25 x = -x;
26 negate = true;
27 }
28
29 bool invert = 0;
30 if (x > 1.0)
31 {
32 x = 1.0 / x;
33 invert = true;
34 }
35
36 // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
37
38 double x2 = x * x;
39 double result = 0.0;
40 double term = x;
41 int sign = 1;
42 for (int i = 1; i <= 100; i += 2)
43 {
44 result += sign * term / i;
45 term *= x2;
46 sign = -sign;
47 if (fabs(term / i) < 1e-16)
48 {
49 break;
50 }
51 }
52
53 if (invert)
54 {
55 result = M_PI_2 - result;
56 }
57
58 return negate ? -result : result;
59}
double atan(double x)
Definition atan.c:5
#define isinf(x)
Definition math.h:37
#define isnan(x)
Definition math.h:39
#define NAN
Definition math.h:20
double fabs(double x)
Definition fabs.c:3
#define M_PI_2
Definition math.h:12
int64_t x
Definition main.c:152