Here’s a quick and dirty post for Pi Day which uses Python code by David Bau (http://davidbau.com/archives/2010/03/14/python_pipy_spigot.html) to compute pi to an arbitrary number of digits. The code implements a “spigot algorithm” developed by Jeremy Gibbons (http://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf). This algorithm can generate the nth digit of pi independently from the preceding digits and runs O(n) in time.
In honor of Pi Day, I ran the code on a Raspberry Pi 3. I slightly modified the calling function to write the generated digits to files in batches of 10000. The computations get slower as the decimal place gets larger. I didn’t time the code exactly, but the time stamps on the files written indicate the first 10000 digits took less than 1 minute, the next 10000 took approximately 2 minutes, then 4 minutes, 6 minutes, 8 minutes, 12 minutes, etc…
Sure you could find and download pi from some online source, but it’s much more fun to do it yourself. I’m running it on my Raspberry Pi 3 right now, and plan to write a another quick and dirty project by tomorrow display them in some way for Pi Day.
Modified source code is below (original code on David Bau’s blog)
[code language=”python”]
#Pi digit generator function
def pi_decimal_digits():
q, r, t, j = 1, 180, 60, 2
while True:
u, y = 3*(3*j+1)*(3*j+2), (q*(27*j-12)+5*r)//(5*t)
yield y
q, r, t, j = 10*q*j*(2*j-1), 10*u*(q*(5*j-2)+r-y*t), t*u, j+1
#Caller program writes digits to disk in batches of 10000
count, digits = 0, pi_decimal_digits()
n_per_file = 10000
while 1:
fn = “pidigits_” + str(count+1) + “_to_” + str(count + n_per_file) + “.txt”
f = open(fn, ‘w’)
print “at ” + str(count)
with open(fn, ‘w’) as f:
for j in xrange(n_per_file):
f.write(str(digits.next()))
f.close()
count += n_per_file
[/code]
Hi Debra, I´ve been a follower of your blog for long time. It´s really interesting and very useful.
Thank you very much!