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?

Recommended Answers

All 2 Replies

I couldn't find the error, but I changed the code a little bit, this one works

#!/usr/bin/env python
# -*-coding: utf8-*-

import math

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

def series_term(k):
    a=factorial(4*k)
    b=(1103+26390*k)
    c=factorial(k)
    d=c**4
    e=396**(4*k)
    return float(a*b)/(d*e)

def estimatePi():
    k=0
    final=0
    while True:
        print "k: ", k
        term = series_term(k)
        final += term
        if term < 1.0e-15:
            break
        else:
            k += 1
    f=2*math.sqrt(2)/9801 # compute this only once
    pi = 1.0/(final * f)
    return pi

if __name__=="__main__":
    print(repr(estimatePi()))

""" my output -->
k:  0
k:  1
k:  2
k:  3
3.141592653589793
"""

I had to explicitely use float() to avoid an integer division issue which led to the same result as yours. Notice that your result is obtained with k=0 only.

Edit: rewrite your factorial function in a non recursive way. It's much better.

commented: great +10

Thank you Gribouillis, :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.