PI generator (update)

vegaseat

This is an update of an earlier version. In this version the string containing the approximated pi value is created directly from the iteration of the generator. This way the program is simplified and can be used with Python2 and Python3 ...

391 Views
About the Author

Scientist

# a generator to approximate pi to n decimals
# tested with Python 2.5.4 and Python 3.1.1  by vegaseat

def pi_generate():
    """
    generator to approximate pi
    returns a single digit of pi each time iterated
    """
    q, r, t, k, m, x = 1, 0, 1, 1, 3, 3
    while True:
        if 4 * q + r - t < m * t:
            yield m
            q, r, t, k, m, x = \
            (10*q, 10*(r-m*t), t, k, (10*(3*q+r))//t - 10*m, x)
        else:
            q, r, t, k, m, x = \
            (q*k, (2*q+r)*x, t*x, k+1, (q*(7*k+2)+r*x)//(t*x), x+2)


# number of decimal digits desired
# used 56 here to make it display well, n can be much higher
n = 56
pi_str = ""
for ix, v in enumerate(pi_generate()):
    #print(v)  # test
    if ix > n:
        break
    pi_str += str(v)

# use string slicing to insert the missing period at index 1
pi_str = pi_str[0] + '.' + pi_str[1:]

print( "pi approx. to %d decimals (below it is published pi):" % n )
print( pi_str )

# published pi value
pi_pub = "3.14159265358979323846264338327950288419716939937510582097"
print( pi_pub )

"""my result -->
pi approx. to 56 decimals (below it is published pi):
3.14159265358979323846264338327950288419716939937510582097
3.14159265358979323846264338327950288419716939937510582097
"""
Be a part of the DaniWeb community

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