Skip to content

Instantly share code, notes, and snippets.

@wasi0013
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wasi0013/76dd692ae3823ac7345a to your computer and use it in GitHub Desktop.
Save wasi0013/76dd692ae3823ac7345a to your computer and use it in GitHub Desktop.
Calculates digits of pi using the Gauss-Legendre Algorithm
__author__ = "wasi0013"
'''
Calculates digits of pi using the Gauss-Legendre Algorithm
Link: https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm
'''
import decimal
import requests, bs4
url = 'http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits.html'
dec = decimal.Decimal
#set precision
decimal.getcontext().prec = 2000
# Retrieves 10000 digits of pi from the website : http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits.html
def get_pi():
response = requests.get(url)
soup = bs4.BeautifulSoup(response.text)
for i in soup.findAll(['p', 'center', 'h1', 'br', 'hr', 'a']):
i.extract()
return "".join(str(soup.body.getText()).strip().split())
# Implementation of the Gauss Legendre Algorithm
def make_pi(pi = None):
a, b = 1, 1/dec(2).sqrt()
p, t = 1, 1/dec(4)
while True:
an, b = (a+b)/2, (a*b).sqrt()
t -= (a-an)*(a-an) * p
a, p = an, p*2
old_pi = pi
pi = (a+b)*(a+b) / (4*t)
if old_pi == pi: return pi
def test_pi(value=None):
correct_digit_count = 0
pi_value = get_pi()
if value:
try:
for i,digit in enumerate(value):
if digit==pi_value[i]: correct_digit_count+=1
else:
break
except:
pass
return correct_digit_count
calculated_pi = str(make_pi())
#prints correct digit counts (including the dot)
print(test_pi(calculated_pi))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment