Little clean up of vegaseat's code for generating pi decimals. Added number of decimals desired and string type return for easy use with ''.join()

``````# a generator to approximate pi to n decimals
# tested with Python 2.5.4 and Python 3.1.1  by vegaseat http://www.daniweb.com/software-development/python/code/249177
# tested with Python 2.7.1 and Python 3.2 by tonyjv (line continuations removed, num_dec, str added)
def pi_generate(num_dec):
"""
generator to approximate pi

returns a single digit as character of pi each time iterated until num_dec generated

"""
n, q, r, t, k, m, x = 0, 1, 0, 1, 1, 3, 3
while True:
if 4 * q + r - t < m * t:
yield str(m)
n += 1
if n > num_dec: return
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 = ''.join(pi_generate(n))
# 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):
%s
3.14159265358979323846264338327950288419716939937510582097""" % (n, pi_str))``````

Is this the formula found here?

commented: very good question +13

To cheat install sympy module and do:

``````from sympy.mpmath import *
mp.dps = 1000
print(pi)``````