Skip to content

Instantly share code, notes, and snippets.

@kenluck2001
Created September 11, 2012 07:14
Show Gist options
  • Save kenluck2001/3696618 to your computer and use it in GitHub Desktop.
Save kenluck2001/3696618 to your computer and use it in GitHub Desktop.
Gauss Legendre iterative algorithm This repeats the given calculation a number of times until it converges at the desired output. This is faster than infinitive series algorithm although consume more memory like in our solution. The size of the list
#!/usr/bin/python
import math
import decimal
def calculatePi (num_of_iteration):
"""
Gauss Legendre iterative algorithm
This repeats the given calculation a number of times until it converges at the desired output. This is faster than infinitive series algorithm although consume more memory like in our solution. The size of the list increases and that affect space complexity.
"""
list_a, list_b, list_t, list_p = [], [], [], []
a_0, b_0, t_0, p_0 = 1.0, (1 / math.sqrt(2.0)), 0.25, 1.0
list_a.append(a_0)
list_b.append(b_0)
list_t.append(t_0)
list_p.append(p_0)
for pos in range(0, num_of_iteration):
a_next = (list_a[pos] + list_b[pos] ) / 2.0
list_a.append(a_next)
b_next = math.sqrt(list_a[pos] * list_b[pos] )
list_b.append(b_next)
t_next = list_t[pos] - (list_p[pos] * (list_a[pos] - a_next)**2 )
list_t.append(t_next)
p_next = 2 * list_p[pos]
list_p.append(p_next)
pi = ((list_a[-1] + list_b[-1])**2) / (4 * list_t[-1] )
d = decimal.Decimal(pi)
return '%.50f' % d
if __name__ == '__main__':
num_of_iteration = 50
piValue = calculatePi (num_of_iteration)
print piValue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment