Search code examples
pythonpi

pyschools Topic 5


Write a function estimatePi() to estimate and return the value of Pi based on the formula found by an Indian Mathematician Srinivasa Ramanujan. It should use a while loop to compute the terms of the summation until the last term is smaller than 1e-15. The formula for estimating Pi is given below: As per Ramanujam's estimation

(I'm sorry, I'm unable to upload the image)

def estimatePi():
import math
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
k=0
final=0
pi=0
while pi<1e-15:
    a=factorial(4*k)
    b=(1103+26390*k)
    c=factorial(k)
    d=c**4
    e=396**(4*k)
    f=2*math.sqrt(2)/9801
    final+=(a*b*f)/(d*e)
    k+=1
    pi=1/final
return pi

and, my problem is this: Expected answer was =3.14159265359 my answer is =3.14159273001

I was not able to find my fault :(. Can anyone help with this for me?


Solution

  • You answer is correct. Float numbers have problems with accuracy especially for large number of digits after the decimal point; and when calculating non-exact values.

    You can see from your answer that it has estimated the value of pi correctly for 5 digits after the decimal.