Skip to content

Instantly share code, notes, and snippets.

Created December 6, 2012 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/4221380 to your computer and use it in GitHub Desktop.
Save anonymous/4221380 to your computer and use it in GitHub Desktop.
Gauss-Legendre Algorithm
# Zach Champion
# Calculus II - Honors Calculus Project
# A script in Python that returns a decimal expansion of pi using the
# Gauss-Legendre algorithm.
from __future__ import with_statement
# Used the decimal module for increased accuracy that the standard float
# type doesn't offer.
import decimal
def pi_gauss_legendre():
D = decimal.Decimal
with decimal.localcontext() as ctx:
ctx.prec += 2
a, b, t, p = 1, 1/D(2).sqrt(), 1/D(4), 1
pi = None
while 1:
an = (a + b) / 2
b = (a * b).sqrt()
t -= p * (a - an) * (a - an)
a, p = an, 2*p
piold = pi
pi = (a + b) * (a + b) / (4 * t)
if pi == piold:
break
return +pi
# Requests user input for how many decimal places you want an expansion to.
x = int(raw_input("Enter an integer to indicate how far to expand pi: "))
# The variable x is later used to dictate how many times the function defined
# above loops through the algorithm. Each time it loops it gives another decimal
# position
decimal.getcontext().prec = x
print pi_gauss_legendre()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment