pythontaylor-series

Taylor series of cos x expansion in python


I want to calculate the summation of cosx series (while keeping the x in radian). This is the code i created:

import math
def cosine(x,n):
    sum = 0
    for i in range(0, n+1):
        sum += ((-1) ** i) * (x**(2*i)/math.factorial(2*i))
    return sum

and I checked it using math.cos() . It works just fine when I tried out small numbers:

print("Result: ", cosine(25, 1000))
print(math.cos(25))

the output:

Result: 0.991203540954667 0.9912028118634736

The number is still similar. But when I tried a bigger number, i.e 40, it just returns a whole different value.

Result: 1.2101433786727471 -0.6669380616522619

Anyone got any idea why this happens?


Solution

  • The error term for a Taylor expansion increases the further you are from the point expanded about (in this case, x_0 = 0). To reduce the error, exploit the periodicity and symmetry by only evaluating within the interval [0, 2 * pi]:

    def cosine(x, n):
        x = x % (2 * pi)
        total = 0
        for i in range(0, n + 1):
            total += ((-1) ** i) * (x**(2*i) / math.factorial(2*i))
        return total
    

    This can be further improved to [0, pi/2]:

    def cosine(x, n):
        x = x % (2 * pi)
        if x > pi:
            x = abs(x - 2 * pi)
        if x > pi / 2:
            return -cosine(pi - x, n)
        total = 0
        for i in range(0, n + 1):
            total += ((-1) ** i) * (x**(2*i) / math.factorial(2*i))
        return total