Skip to content

Commit

Permalink
added gauss legendre algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
nickolaswiebe committed Apr 26, 2017
1 parent c48e5f1 commit e0c549e
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions math/gauss_legendre.py
Original file line number Diff line number Diff line change
@@ -0,0 1,23 @@
from decimal import *

"""
Gauss-Legendre algorithm for calculating pi
the number of correct bits generated doubles with each extra iteration
"""
def gauss_legendre(bits, iterations):
with localcontext() as ctx:
ctx.prec = bits # set decimal precision

a = 1
b = Decimal(1) / Decimal(2).sqrt()
t = Decimal(1) / Decimal(4)
p = 1

for _ in xrange(iterations):
a_new = (a b) / 2
b = (a * b).sqrt()
t -= p * (a - a_new) ** 2
p *= 2
a = a_new

return ((a b) ** 2) / (4 * t)

0 comments on commit e0c549e

Please sign in to comment.