pythontaylor-series

Taylor series Sin(X) with tolerance with python


The task for my problem is to continue the Taylor series until the tolerance value is met.

The first two iterations goes as planned however when c = 2 and onward the x value is not correct.

If the code is executing correct the loop should be approaching tol.

Any help is appreciated

import math

x = math.pi/2
tol = 0.01
s = math.sin(x)

Total = 0
c = 0

while (abs(Total - s))>= tol:
    x = ((-1)**c) * (x**(2*c+1))/(math.factorial(2*c+1))   
    Total+=x
    c+=1
        
        
print(Total)
print(c)

I tried manipulating different variables but to no avail.


Solution

  • In this loop:

    while (abs(Total - s))>= tol:
        x = ((-1)**c) * (x**(2*c+1))/(math.factorial(2*c+1))   
        Total+=x
        c+=1
    

    You overwrite your value of 'x' which was meant to hold the angle for the Taylor expansion.

    Instead try just making a new variable to add to your total:

    while (abs(Total - s))>= tol:
        term = ((-1)**c) * (x**(2*c+1))/(math.factorial(2*c+1))   
        Total += term
        c+=1