FlatAssembler
FlatAssembler

Reputation: 782

Attempt to calculate cosine using Taylor Series is very imprecise

So, I have tried to write a program in C which will approximate the cosine using the Taylor series:

#include <stdio.h>
#include <math.h>

int main() {
  printf("degrees\tTaylor\tcos(degrees)\n");
  for (double i=0; i<=90; i++) {
  double factorial=1;
  double x,xn=1;
  x=i/(180/M_PI);
  double y=1;
  for (int i=1; i<30; i++) {
    factorial*=i;
    xn*=x;
    y+=((i%3==0)?(1):(i%3==1)?(0):(-1))*xn/factorial;
  }
  printf("%lf\t%lf\t%lf\n",i,y,cos(x));
  }
}

However, the error for 90 degrees is more than 1/3:

The error grows very fast

I thought the error was due to numeric instability caused by the C double type. However, when I rewrote my program into Python, I got nearly the same result:

import math
print("degrees\tTaylor\tcos(degrees)\tdeviance")
for degrees in range(0,90+1):
  factorial=1
  x=degrees/(180/math.pi)
  xn=1
  y=1
  for i in range(1,50):
    factorial=factorial*i
    xn=xn*x
    multiplicator=0
    if i % 3 == 0:
      multiplicator=1
    elif i % 3 == 1:
      multiplicator=0
    else:
      multiplicator=-1
    y=y+multiplicator*xn/factorial
  print(str(degrees)+"\t"+str(y)+"\t"+str(math.cos(x))+"\t"+str(abs(y-math.cos(x))))

Do you have any idea what is going on here? By using the first 50 terms from the Taylor Series, it should be nearly indistinguishable from the real cosine function. But it is not.

Upvotes: 0

Views: 111

Answers (1)

Frank Yellin
Frank Yellin

Reputation: 11230

Your bug is the i % 3. The terms for cosine go 1, 0, -1, 0, 1, 0, -1, 0....

Upvotes: 1

Related Questions