Reputation: 27
I have this academic project in C language. One of the exercises is calculating cos(x) without using math.h. For that, we're given a series (which I presume it's a Taylor/Maclaurin) for cos(x). For standard input, we have x angles, and k iterations. The sum is from n=0 to k-1 of ((-1)^n*x^(2n))/(2n)!
I've tried changing in and out of cycles and fiddling with variables with no avail.
Here is the code (UPDATED):
#include <stdio.h>
int fat(int num) {
int fat_num=1;
for (int cnt=1; cnt<=num; cnt++) fat_num*=cnt;
return fat_num;
}
float expn(int x, int y) {
int x_y=x;
for (int cnt=1; cnt<y; cnt++) x_y*=x;
return x_y;
}
int main() {
const float pi = 3.1415926;
float x;
scanf("%f",&x);
int k;
scanf("%d", &k);
float cosx = 0;
int n = 0;
x *= pi/180;
while (n <= k-1) {
if (n%2 == 0)
cosx += expn(x,2*n)/fat(2*n);
else
cosx += -1*expn(x,2*n)/fat(2*n);
n++;
}
printf("%f", cosx);
return 0;
}
The input of 96 gives me a cossine of 0.54. Which is not right.
Solved: The error was in expn which had to be updated to float!
Upvotes: 0
Views: 79
Reputation: 154087
2 problems
expn(x,2*n)/fat(2*n)
uses integer division.
float expn(int x, int y)
uses an int x
. Need floating point x
.
// int expn(int x, int y) {
float expn(float x, int y) {
float x_y = 1;
for (int cnt = 0; cnt < y; cnt++)
x_y *= x;
return x_y;
}
Code has various efficiencies.
An alternative that does not need k
- some food for thought.
static double my_cos_helper(double xx, double term, unsigned n) {
if (term + 1.0 == 1.0) {
return term;
}
return term - xx * my_cos_helper(xx, term / ((n + 1) * (n + 2)), n + 2);
}
double my_cos(double x) {
return my_cos_helper(x * x, 1.0, 0);
}
Upvotes: 1