Taylor series Sin(X) with tolerance with python

Question:

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.

Asked By: Chicken_Cutlet

||

Answers:

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
Answered By: Shaun Ramsey
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.