We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent c48e5f1 commit e0c549eCopy full SHA for e0c549e
1 file changed
math/gauss_legendre.py
@@ -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