python - 为什么使用相同算法计算 pi 的两个代码的运行时间不同?

标签 python time-complexity

沃利斯公式也用于计算 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/

相关文章:

php - 在 Python 中存储唯一字符

python - 如何使用 ElementTree 递归迭代 Python 中的 XML 标签?

python - 关闭在对象初始化中打开的文件的正确方法是什么?

python - 仅在一个方向上使用膨胀?

python - 选择表中按 Pandas 分组的行

c# - Math.Sqrt() 的时间复杂度?

c++ - 有 break 语句时如何计算时间复杂度

algorithm - 什么会导致算法具有 O(log log n) 复杂度?

string - 确定序列是否是两个字符串重复的交错

python - 检查序列是否包含非连续子序列的最快方法?