double mycos(double x,double eps) { double s,an; int n; n=0; an=1; s=0; while(fabs(an)>eps) { s+=an; n++; an*=-x*x/(2.*n-1.0)/(2.0*n); } return s; }

+6 votes

Best answer

What do you mean by "make it work"?

Using your function in the following scenario seems to work.

#include <stdio.h> #include <math.h> #define PI 3.1415926535897932384626433832795 double mycos(double x, double eps) { double s = 0.0 double an = 1.0; int n = 0; while (fabs(an) > eps) { s += an; n++; an *= - x * x / (2.0 * n - 1.0) / (2.0 * n); } return s; } int main() { printf("cos(60) = %lf\n", mycos(PI / 3, 0.1)); return 0; }

And the result is

cos(60) = 0.451689

It seems to be more or less correct (with a certain error level).

You can test it with various inputs and see where it makes mistakes (for instance instead of using PI / 3 radians, using 60 radians returns a wrong value). (Note: first I thought it calculates in degrees, hence I used 60 radians -- which I wrongly thought was 60 degrees and that's how I found this input to produce erroneous output.)

...