在 Python 中将 float 转换为 int 结果错误答案

Cast float to int in Python results wrong answer

我有一个正在计算的算法:

result = int(14949283383840498/5262*27115)

正确的结果应该是 77033412951888085,但是 Python3.8 给了我 77033412951888080

我也试过以下方法:

>>> result = 77033412951888085
>>> print(result)
77033412951888085
>>> print(int(result))
77033412951888085
>>> print(float(result))
7.703341295188808e+16
>>> print(int(float(result)))
77033412951888080

问题似乎是在我将float 转换为int 时出现的。我错过了什么?

PS:我发现使用 result = 14949283383840498//5262*27115 我得到了正确的答案!

选角不是问题。浮点运算在精度方面存在局限性。参见 https://docs.python.org/3/tutorial/floatingpoint.html

需要使用整数除法或使用默认使用 28 位精度的 decimal 模块。

使用整数除法

result = 14949283383840498 // 5262 * 27115
print(result)

输出:

77033412951888085

使用十进制模块

from decimal import Decimal
result = Decimal(14949283383840498) / 5262 * 27115
print(result)

输出:

77033412951888085

这是一个精度限制:

result = 14949283383840498/5262*27115
result
7.703341295188808e+16

在这种情况下,结果是一个浮点数。 可以看到精度是15位。 转换成int,你看最后一个非零数字是8,结果是正确的:float show when printing.

尝试以下操作:

print(sys.float_info.dig)
15

dig 是可以用浮点数忠实表示的最大小数位数。

有关此问题的非常好的解释可用 here

但是 Python 有一些方法可以做得更好,请参阅 Python 的 doc:

For use cases which require exact decimal representation, try using the decimal module which implements decimal arithmetic suitable for accounting applications and high-precision applications.

Another form of exact arithmetic is supported by the fractions module which implements arithmetic based on rational numbers (so the numbers like 1/3 can be represented exactly).

If you are a heavy user of floating point operations you should take a look at the NumPy package and many other packages for mathematical and statistical operations supplied by the SciPy project