[Solved] How to find value of this series using python?


This is the Taylor’s series development of exp(-x). Recognizing this gives you a good opportunity to check your result against math.exp(-x).

Simple syntax improvements

You don’t need an ‘else’ after the while. Just add the code to be run after the loop at the same indentation level as before the while loop.

Mathematical problems

Most importantly, the computing of the factorial is simply never done. Writing p*i does not store in p the product of p and i. You need to do that.

Then, there is a problem with the operator precedence. When you write pow(...)/p*i, Python understands ( pow(...) / p ) * i, which is not what you mean.

Finally, most of the terms in the series cancel out, but you add all positive terms on one side and all negative terms on the other. This means that you will grow two very big values (and risk overflows if you were using integers), and then take the difference between them to get the result. Because double precision on a computer is finite, this is a bad practice precision-wise. It is better to keep all the terms in your sum with the same sort of orders of magnitudes.

Improved for correctness

import math
a=input("Enter the no")
x=input("Enter value of x")
s=1
p=1
for i in range(1,a):
    p=p*i
    if(i%2!=0):
        s=s-math.pow(x,i)/p
    else:
         s=s+math.pow(x,i)/p
print s
print math.exp(-x)

Note how the use of a for loop and less intermedis-ry sums makes it all easier to read.

Removing the branch

pow(-x,i) is negative if i is uneven, positive otherwise. Thus -pow(x,i) if i%2 != 0 else pow(x,i) can be rewritten pow(-x,i). Removing an if in an inner loop is (almost ?) always a good thing, for performance. So a simplified version is :

import math
a=input("Enter the no")
x=input("Enter value of x")
s=1
p=1
for i in range(1,a):
    p=p*i
    s=s+math.pow(-x,i)/p
print s
print math.exp(-x)

That also has the benefit of making the code shorter (and thus more readable).

0

solved How to find value of this series using python?