Skip to content

Instantly share code, notes, and snippets.

@z-------------
Last active August 29, 2015 14:24
Show Gist options
  • Save z-------------/81536abc10e1816437a5 to your computer and use it in GitHub Desktop.
Save z-------------/81536abc10e1816437a5 to your computer and use it in GitHub Desktop.
Ways of computing the value of Pi in Python (Pithon. geddit?)
#!/usr/bin/env python3
'''
the Gregory-Leibniz series
slower than Nilakantha's in terms of rate of convergence
pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 ...
'''
import math
denominator = 1
sum = 0
sign = 1
i = 1
while True:
sum += sign * 1 / denominator
sum_times_four = sum * 4
error = str(abs(math.pi - sum_times_four) * 100) + "%"
print("{i} | {sum} ({error})".format(i=i, sum=sum_times_four, error=error))
denominator += 2
if sign is 1:
sign = -1
else:
sign = 1
i += 1
#!/usr/bin/env python3
'''
math.pi
not much to say about this
i swaer this isn't cheating
'''
import math
print("{i} | {val} ({error})".format(i=1, val=math.pi, error="0%"))
#!/usr/bin/env python3
'''
Nilakantha's series
faster than Gregory-Leibniz in terms of rate of convergence
pi = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) ...
'''
import math
sum = 3
dff = 2 # first factor of the denominator
sign = 1
i = 1
while True:
sum += sign * 4 / (dff * (dff + 1) * (dff + 2))
error = str(abs(math.pi - sum) * 100) + "%"
print("{i} | {sum} ({error})".format(i=i, sum=sum, error=error))
dff += 2
if sign is 1:
sign = -1
else:
sign = 1
i += 1

Ways of computing the value of Pi in Python (Pithon. geddit?)

Featuring:

  • Gregory-Leibniz series
  • Nilakantha's series
  • math.pi (this counts, right?)
  • possibly more in the future
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment