pythontaylor-series

Expanding taylor series using relation between successive terms with a specified tolerance in spyder


I have used this code to determine the value of e^pi with a specified tolerance in spyder(Python 3.8).

from math import*
term=1
sum=0
n=1
while (abs(e**pi-term))>0.0001:
    term=term*pi/n
    sum+=term
    n+=1
print(sum,e**pi)

I ran this code several times. But spyder is not showing anything when I run this code. I am new to python. So now I have no way to know whether this code is correct or not. It would be beneficial if you could verify whether this code is valid or not.


Solution

  • Okay, so the taylor series for e^x is sum n=0 to inf of x^n / n! which you seem to be doing correctly by multiplying by pi/n during each iteration.

    One problem I noticed was with your while loop condition. To check the error of the function, you should be subtracting your current sum from the actual value. This is why you enter the infinite loop, because your term will approach 0, so the difference will approach the actual value, e^pi, which is always greater than .0001 or whatever your error is.

    Additionally, since we start n at 1, we should also start sum at 1 because the 0th term of the taylor series is already 1. This is why you enter the infinite loop, because

    Therefore, our code should look like this:

    from math import*
    term = 1
    sum = 1
    n = 1
    while (abs(e ** pi - sum)) > 0.0001:
        term = term * pi / n
        sum += term
        n += 1
    print(sum,e**pi)
    

    Output:

    23.140665453179782 23.140692632779263
    

    I hope this helped answer your question! Please let me know if you need any further clarification or details :)