沃利斯公式也用于计算 PI。为什么两种方法的运行时间相差这么大?
公式的链接是http://en.wikipedia.org/wiki/Wallis_product
非常感谢! 代码如下:
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)
以下输出
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
最佳答案
第二个版本仅使用整数,它是作为 BigNum 实现的,因此速度要慢得多。这完全是矫枉过正,除非你希望获得巨大的准确性(但考虑到沃利斯的收敛速度非常慢,这是完全没有希望的)。
通过将其添加到循环中
if i & 15 == 0:
den= math.frexp(den)[0]
num= math.frexp(num)[0]
这是输出:
3.141592653589793
3.141584799578707
7.854011085939305e-06
Running time: 0.033463999999999994
3.141592653589793
3.1415847995786645
7.85401112857187e-06
The error between the two results: 4.263256414560601e-14
Running time: 0.0331592
关于python - 为什么使用相同算法计算 pi 的两个代码的运行时间不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71395610/