0

Q. ) 1 + 1 / 2! + 1/ 3! + ¼! + ….....
The output of the following program is always 1.0. I'm a python beginner. Please tell me what's wrong? Please suggest any other methods to make this program better. No inbuilt functions, please. I want to do this manually.

    n=int(raw_input("Enter number of terms : ")) 

    d=0  #to sum all terms, initial value is 0

while n>0:
     j=n   #we start by taking factorial of the last term
     s=1   #to multiply to find factorial
     while j>0:
               s=s*j   #number gets multiplied to s and stored in s
               j=j-1   #number is decreased until it reaches 0
     n=n-1   #we will keep finding factorial until the very first term, i.e. 1 is reached
     x=float(1/s)   #to find reciprocal of the factorial we just found in     floating point
     d=d+x #adding to final sum

print "Sum of 1+1/2!+1/3!+1/4!+.... is ",d #printing

1 Answers1

1

You need to use float somewhere in your division. I just make you "s" a float.

n=int(raw_input("Enter number of terms : ")) 

d=0  #to sum all terms, initial value is 0

while n>0:
     j=n   #we start by taking factorial of the last term
     s=float(1)   #to multiply to find factorial
     while j>0:
               s=s*j   #number gets multiplied to s and stored in s
               j=j-1   #number is decreased until it reaches 0
     n=n-1   #we will keep finding factorial until the very first term, i.e. 1 is reached
     x=1/s   #to find reciprocal of the factorial we just found in     floating point
     d=d+x #adding to final sum

print "Sum of 1+1/2!+1/3!+1/4!+.... is ",d #printing
wilfriedroset
  • 217
  • 1
  • 8