Taylor Series in C

J. Herrera picture J. Herrera · Aug 27, 2011 · Viewed 9.4k times · Source

I'm trying to make a program to calculate the cos(x) function using taylor series so far I've got this:

int factorial(int a){

if(a < 0)
    return 0;
else if(a==0 || a==1)
    return 1;
else
    return a*(factorial(a-1));
}

double Tserie(float angle, int repetitions){
    double series = 0.0;
    float i;

for(i = 0.0; i < repeticiones; i++){
    series += (pow(-1, i) * pow(angle, 2*i))/factorial(2*i);
    printf("%f\n", (pow(-1, i) * pow(angle, 2*i))/factorial(2*i));
}
return series;

}

For my example I'm using angle = 90, and repetitions = 20, to calculate cos(90) but it's useless I just keep getting values close to the infinite, any help will be greatly appreciated.

Answer

Blindy picture Blindy · Aug 27, 2011

For one thing, the angle is in radians, so for a 90 degree angle, you'd need to pass M_PI/2.

Also, you should avoid recursive functions for something as trivial as factorials, it would take 1/4 the effort to write it iteratively and it would perform a lot better. You don't actually even need it, you can keep the factorial in a temporary variable and just multiply it by 2*i*(2*i-1) at each step. Keep in mind that you'll hit a representability/precision wall really quickly at this step.

You also don't need to actually call pow for -1 to the power of i, a simple i%2?1:-1 would suffice. This way it's faster and it won't lose precision as you increase i.

Oh and don't make i float, it's an integer, make it an integer. You're leaking precision a lot as it is, why make it worse..

And to top it all off, you're approximating cos around 0, but are calling it for pi/2. You'll get really high errors doing that.