简体   繁体   English

Python中的整数与浮点乘法

[英]Integer vs floating point multiplication in Python

I recently wrote a short Python program to calculate the factorial of a number as a test to see how much faster integer multiplication is compared to floating point multiplication.我最近编写了一个简短的 Python 程序来计算一个数字的阶乘,作为测试,看看整数乘法比浮点乘法快多少。 Imagine my surprise when I observed that it was the floating point multiplication that was faster!想象一下当我观察到浮点乘法速度更快时我的惊讶! I'm puzzled by this and am hoping someone can enlighten me.我对此感到困惑,希望有人能启发我。 I'm using exactly the same function for the factorial calculation and simply passing it a float versus an integer.我使用完全相同的函数进行阶乘计算,并简单地将浮点数与整数传递给它。 Here is the code:这是代码:

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.")

When I run this program the results vary, but by and large the integer calculation comes out faster most of the time, which is counter to everything I thought I knew (keep in mind, I'm no expert).当我运行这个程序时,结果会有所不同,但总的来说,大多数情况下整数计算的速度更快,这与我认为我知道的一切相反(请记住,我不是专家)。 Is there something wrong with my method of timing the calculation?我的计算时间方法有问题吗? Do I need to run the calculation thousands of times to get a more accurate measure of the time?我是否需要运行数千次计算才能更准确地测量时间? Any insight would be appreciated.任何见解将不胜感激。

Thanks for the comments, and the tip about using timeit.感谢您的评论,以及有关使用 timeit 的提示。 When I rerun the code using timeit, I find results similar to what Seb mentions.当我使用 timeit 重新运行代码时,我发现结果与 Seb 提到的类似。 Namely, the integer calculations are faster for small values (for me, up to about 15) and then the floats are faster (becoming significantly faster for larger values).也就是说,整数计算对于小值(对我来说,最多大约 15)更快,然后浮点数更快(对于更大的值变得明显更快)。 This is exactly as I would have expected!这正是我所期望的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM