-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmath.c
More file actions
83 lines (70 loc) · 1.53 KB
/
math.c
File metadata and controls
83 lines (70 loc) · 1.53 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
#include "math.h"
/* Returns an approximation of the sine of the argument.
* @param deg: the angle in degrees
*/
float sin(float rad){
float deg = rad_to_deg(rad);
// Taylor series approximation
float sin = deg;
float term = deg;
int i;
for(i = 1; i < 10; i++) {
term *= -1 * deg * deg / ((2 * i + 1) * (2 * i));
sin += term;
}
return deg_to_rad(sin);
}
/* Returns an approximation of the sine of the argument.
* @param deg: the angle in degrees
*/
float cos(float rad){
float deg = rad_to_deg(rad);
// Taylor series approximation
float cos = 1;
float term = 1;
int i;
for(i = 1; i < 10; i++) {
term *= -1 * deg * deg / ((2 * i) * (2 * i - 1));
cos += term;
}
return deg_to_rad(cos);
}
float tan(float rad){
return sin(rad)/cos(rad);
}
float deg_to_rad(float deg){
return deg * DR;
}
float rad_to_deg(float rad){
return rad / DR;
}
/* Returns the square root of the argument.
* @param n: the number to take the square root of
*/
float sqrt(float n) {
float x = n/2;
// int x = pow(2, ceil(numbits(n)/2));
int i, y;
for(i = 0; i < 50; i++) {
int y = floor((x + floor(n/x))/2);
if (y >= x) {
return x;
}
x = y;
}
return x;
}
float pow(float base, float exponent){
float result = 1;
int i;
for(i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
float floor(float x){
return (int) x;
}
float ceil(float x){
return (int) x + 1;
}