Reputation: 2456
Need some help with a task from my homework. They gave us a series to calculate cosine, which is: Σ(-1)^ix^2i/(2i)! And the task is to implement this in C program by writing a function that takes angle x, and calculate it's cosine. The series should continue summing until the next addend in the series is less then 1.0e-6 (0.000001). I did this and it works good only for small numbers, if I put big numbers as angle, the program get stuck.
#include <stdio.h>
#include <math.h>
#define PI 3.141592
double my_cos(double angle);
int main() {
double angle, radian, my_res, their_res;
printf("Please type a number... \n");
scanf("%lf", &angle);
radian = angle * (PI/180);
my_res = my_cos(radian); /* result from my custom cosine function */
their_res = cos(radian); /* result from the cos function located in the library math.h */
printf("My result is: %f \nMath.h library result is: %f \n", my_res, their_res);
return 0;
}
.
#include <math.h>
#define ACCURACY 1.0e-6
long factorial(int x);
double my_cos(double angle){
int i = 0;
double sum = 0, next_addend;
do {
next_addend = pow(-1, (i+1)) * pow(angle, 2*(i+1)) / factorial(2*(i+1));
sum += pow(-1, i) * pow(angle, 2*i) / factorial(2*i);
i++;
} while ( ACCURACY < fabs(next_addend) );
return sum;
}
/* return the factorial of a given value */
long factorial(int x){
if ( x == 0 ) {
return 1;
}
return(x * factorial(x - 1));
}
If I run the program and insert 45:
But if I insert 300, the program is just "waiting":
I guess it related somehow to the factorial function? I will really appreciate your help..
Upvotes: 0
Views: 135
Reputation: 18807
Depending on whether sizeof(long)
is 4 or 8 on your system you can only calculate 12! or 20! inside a long
. Also, calculating multiple pow
at every iteration is very inefficient.
For a better solution, try to find out how to calculate the next_addend
if you know the previous addend (hint: calculate their ratio on a piece of paper).
Upvotes: 4