Computing PI can be dated back long long time ago, where without the help of computer, mathematicans can only compute several digts i.e. 15 in months. Later, in 20 century, the digits of PI have been hunt with the help of computers. Some equations of computing PI converge quickly but they are not easy to solve/program. There are two most simple equations to compute PI, One is Gregory-Leibniz Series.
However, this equation converges slower than the Nilakantha method.
The below python code solves the above two equations.
from math import * EPSILON = 0.001 # Nilakantha step = 0 ans = 3 j = 2 while 1: step += 1 if step % 2 == 1: ans += 4.0 / (j * (j + 1) * (j + 2)) else: ans -= 4.0 / (j * (j + 1) * (j + 2)) j += 2 if abs(pi - ans) <= EPSILON: break print step, ans, abs(pi - ans) # Gregory–Leibniz step = 0 ans = 0 j = 1 while 1: step += 1 if step % 2 == 1: ans += 4.0 / j else: ans -= 4.0 / j j += 2 if abs(pi - ans) <= EPSILON: break print step, ans, abs(pi - ans)
The output is:
1 3.16666666667 0.0250740130769 2 3.13333333333 0.00825932025646 3 3.14523809524 0.0036454416483 4 3.13968253968 0.00191011390725 5 3.14271284271 0.00112018912305 6 3.14088134088 0.000711312708452 7 3.14207181707 0.000479163482024 8 3.14125482361 0.000337829982028 9 3.14183961893 0.000246965339609 ... ... 23 3.14161069904 1.804545068e-05 24 3.14157668544 1.5968154762e-05 25 3.14160685135 1.4197757757e-05 26 3.14157997396 1.2679627611e-05 27 3.14160402399 1.13703964391e-05 28 3.14158241825 1.0235342045e-05 1 4.0 0.85840734641 2 2.66666666667 0.474925986923 3 3.46666666667 0.325074013077 4 2.89523809524 0.246354558352 5 3.33968253968 0.198089886093 6 2.97604617605 0.165546477544 7 3.28373848374 0.142145830149 8 3.01707181707 0.124520836518 9 3.25236593472 0.110773281129 10 3.04183961893 0.0997530346604 .... ... ... 992 3.14058458933 0.00100806426003 993 3.14259970268 0.0010070490901 994 3.14058661763 0.00100603596275 995 3.14259767846 0.00100502487184 996 3.14058863778 0.00100401581123 997 3.14259566236 0.00100300877482 998 3.14059064983 0.00100200375651 999 3.14259365434 0.00100100075025
It is obvious that the first method is less efficient than the second one. For Gregory-Leibniz, it takes around 999 iterations to converge to PI with error smaller than 0.001 but the Nilakantha takes just 28 iterations to approach the value.
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Computing Approximate Value of PI using Monte Carlo in Python
Next Post: Codeforces: B. Sum of Digits
This line of code:
print step, ans, abs(pi – ans)
Had to be like this:
print (step, ans, abs(pi – ans))
Otherwise it would error out with syntax issues.
I think, in Python 2.x this is ok.