# Custard Pie

Happy π Day!

```## Pi
##
## Algorithms for calculating the value of Pi
## Written (mostly) on Pi Day 2017

import random
import math
import decimal

precision = 50

D = decimal.Decimal
decimal.setcontext(decimal.Context(prec = precision))

def pi_by_random_numbers(max_number, trials, print_every=10000):
i = 1
cp = 0
while i < trials:
a, b = random.randint(1, max_number), random.randint(1, max_number)
if math.gcd(a, b) == 1: # if random numbers are coprime
cp += 1 # increment coprime counter
i += 1 #increment loop counter
if (i % print_every) == 0:
print((D(6*i)/D(cp)).sqrt())
return (D(6*i)/D(cp)).sqrt()

def pi_by_riemann_zeta(terms, print_every=10000):
i = 1
zsum = D(0)
while i < terms:
zsum += D(1)/(D(i)*D(i))
if (i % print_every) == 0:
print((zsum*D(6)).sqrt())
i += 1
return (zsum*D(6)).sqrt()

def pi_by_bbp(from_digit,to_digit=None):
if to_digit is None or from_digit<0:
from_digit,to_digit=0,abs(from_digit)
if not isinstance(from_digit,int) or from_digit<0:
from_digit=int(abs(from_digit))
if not isinstance(to_digit,int) or to_digit<0:
to_digit=int(abs(to_digit))
def pi_gen():
try:
N = 0
n, d = 0, 1
while True:
xn = (120 * N * N + 151 * N + 47)
xd = (512 * N * N * N * N + 1024 * N * N * N + 712 * N * N + 194 * N + 15)
n = (16 * n * xd + xn * d) % (d * xd)
d *= xd
yield 16 * n // d
N += 1
except KeyboardInterrupt:
print(N)
raise
pi=pi_gen()
s='3.'
if from_digit==0:
print('3.',end='')
for i in range(from_digit):
d=next(pi)
for i in range(from_digit,to_digit):
d=next(pi)
print('0123456789abcdef'[d],end='')
s+='0123456789abcdef'[d]
print()
return s```

This site uses Akismet to reduce spam. Learn how your comment data is processed.