-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrig.cpp
More file actions
126 lines (91 loc) · 2.32 KB
/
trig.cpp
File metadata and controls
126 lines (91 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include "trig.h"
static inline double simplify_rad(double x) {
// Uses the fact that trigonometric functions are periodic to avoid
// calculations with big numbers.
// sin(2pi * k + x) = sin(x)
// cos(2pi * k + x) = cos(x)
// where 0 <= x < 2pi
const double two_pi = 2 * pi;
while (x > two_pi) {
x -= two_pi;
}
return x;
}
double cos(double x) {
// Calculates the cosine of a real number (in radians)
//
// cos(x) = 1 - x^2/2! + x^4/4! + ... + (-1)^n - x^(2n) / (2n)!
// The convergence is given by the alterating series test
x = simplify_rad(x);
if (abs(x) < PRECISION)
return 1;
if (abs(abs(x) - pi) < PRECISION)
return -1;
if (abs(abs(x) - pi / 2.0) < PRECISION)
return 0;
if (abs(abs(x) - 3.0 * pi / 2.0) < PRECISION)
return 0;
int n = 2;
double value = 1;
double x2 = x * x;
double next_term = value * x2 / 2.0;
int sign = 1;
while(abs(next_term) > PRECISION) {
sign = -sign;
value += sign * next_term;
n += 2;
next_term = next_term * x2 / ((double) (n-1) * (n));
}
return value;
}
double sec(double x) {
return 1.0 / cos(x);
}
double sin(double x) {
// Calculates the sine of a real number (in radians)
//
// sin(x) = x - x^3/3! + x^5/5! + ... + (-1)^n - x^(2n+1) / (2n+1)!
// The convergence is given by the alterating series test
x = simplify_rad(x);
if (abs(x) < PRECISION)
return 0;
if (abs(abs(x) - pi) < PRECISION)
return 0;
if (abs(abs(x) - (pi / 2.0)) < PRECISION)
return 1;
if (abs(abs(x) - 3.0 * pi / 2.0) < PRECISION)
return -1;
int n = 3;
double value = x;
double x2 = x * x;
double next_term = value * x2 / 6.0;
int sign = 1;
while(abs(next_term) > PRECISION) {
sign = -sign;
value += sign * next_term;
n += 2;
next_term = next_term * x2 / ((double) (n-1) * (n));
}
return value;
}
double csc(double x) {
return 1.0/sin(x);
}
double tan(double x) {
return sin(x) / cos(x);
}
double cot(double x) {
return cos(x)/sin(x);
}
double radian_to_degree(double o){
// pi * radians = 180 degrees
// 1 * radian = 180 / pi
// o radians = o * (180 / pi)
return o * (180.0 / pi);
}
double degree_to_radian(double o) {
// pi radians = 180 degrees
// 1 degree = pi / 180
// o degrees = o * pi / 180
return o * (pi / 180.0);
}