Skip to content

Commit e0c549e

Browse files
committed
added gauss legendre algorithm
1 parent c48e5f1 commit e0c549e

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

math/gauss_legendre.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from decimal import *
2+
3+
"""
4+
Gauss-Legendre algorithm for calculating pi
5+
the number of correct bits generated doubles with each extra iteration
6+
"""
7+
def gauss_legendre(bits, iterations):
8+
with localcontext() as ctx:
9+
ctx.prec = bits # set decimal precision
10+
11+
a = 1
12+
b = Decimal(1) / Decimal(2).sqrt()
13+
t = Decimal(1) / Decimal(4)
14+
p = 1
15+
16+
for _ in xrange(iterations):
17+
a_new = (a + b) / 2
18+
b = (a * b).sqrt()
19+
t -= p * (a - a_new) ** 2
20+
p *= 2
21+
a = a_new
22+
23+
return ((a + b) ** 2) / (4 * t)

0 commit comments

Comments
 (0)