The Wallis formula is also used to calculate PI. Why are the running times of the two methods so different?
The link to the formula is http://en.wikipedia.org/wiki/Wallis_product
Thank you so much! The following code:
from __future__ import division
import time
# Method 1
T1 = time.perf_counter()
pi = 3.14159265358979312
my_pi = 1.
for i in range(1, 100000):
my_pi *= 4 * i * i / (4 * i * i - 1.)
my_pi *= 2
T2 = time.perf_counter()
print(pi)
print(my_pi)
print(abs(pi - my_pi))
print("Running time:", T2-T1)
# Method2
T3 = time.perf_counter()
num = 1
den = 1
pi = 3.14159265358979312
for i in range(1, 100000):
tmp = 4 * i * i
num *= tmp
den *= tmp - 1
better_pi = 2 * (num / den)
T4 = time.perf_counter()
print(pi)
print(better_pi)
print(abs(pi - better_pi))
print("The error between the two results:", abs(my_pi - better_pi))
print("Running time:", T4-T3)
The following output
3.141592653589793
3.141584799578707
7.854011085939305e-06
Running time: 0.04233423100001232
3.141592653589793
3.1415847995787067
7.854011086383395e-06
The error between the two results: 4.440892098500626e-16
Running time: 23.963929412