为什么使用相同算法计算圆周率的两个代码有不同的 运行 次?

Why do two codes that calculate pi using the same algorithm have different running times?

Wallis 公式也用于计算 PI。为什么两种方法的运行次相差这么大?

公式的link是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

第二个版本只使用整数,它被实现为 BigNums,因此慢得多。这完全是矫枉过正,除非你希望获得巨大的准确性(但鉴于 Wallis 的收敛速度非常慢,这是完全没有希望的)。


通过在循环中添加这个

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