Python 中的整数与浮点乘法

Integer vs floating point multiplication in Python

我最近写了一个简短的 Python 程序来计算一个数的阶乘作为测试,看看整数乘法比浮点乘法快多少。当我观察到更快的是浮点乘法时,想象一下我的惊讶吧!我对此感到困惑,希望有人能启发我。我使用完全相同的函数进行阶乘计算,只是将浮点数与整数传递给它。这是代码:

import time

def fact(n):
    n_fact = n
    while n > 2:
        n_fact *= n - 1
        n -= 1
    print(n_fact)
    return n_fact

n = int(input("Enter an integer for factorial calculation: "))
n_float = float(n)

# integer factorial
start = time.time()
fact(n)
end = time.time()
print("Time for integer factorial calculation: ", end - start, "seconds.")

# float factorial
start = time.time()
fact(n_float)
end = time.time()
print("Time for float factorial calculation: ", end - start, "seconds.")

当我 运行 这个程序时,结果会有所不同,但总的来说,大多数时候整数计算的速度更快,这与我自以为知道的一切背道而驰(请记住,我没有专家)。我计算时间的方法有问题吗?我是否需要 运行 计算数千次才能更准确地测量时间?任何见解将不胜感激。

感谢您的评论,以及有关使用 timeit 的提示。当我使用 timeit 重新运行代码时,我发现结果类似于 Seb 提到的结果。即,对于小值(对我来说,最多约 15),整数计算更快,然后浮点数更快(对于更大的值,变得明显更快)。这完全符合我的预期!