生成一组具有特定公差 python 的小数点时出错

Error in generating a set of decimal point numbers with a particular common difference in python

我试图通过在 python 中编码将其增加 0.001 来获得从零开始的一系列数字。它正确给出结果直到 0.008。在下一次迭代中,该值必须恰好为 0.009,但输出为 0.009000000000000001。这种错误也可以在进一步的迭代中看到。 以下代码:

t = 0.000
dt = 0.001
timemax = 0.012
while(t<timemax):
    print(t)
    t = t + dt
    if(t>= timemax):
        exit()

输出结果如下:

0.0
0.001
0.002
0.003
0.004
0.005
0.006
0.007
0.008
0.009000000000000001
0.010000000000000002
0.011000000000000003

dt = 0.01timemax = 0.12的值时甚至可以看到错误。其代码如下:

t = 0.000
dt = 0.01
timemax = 0.12
while(t<timemax):
    print(t)
    t = t + dt
    if(t>= timemax):
        exit()

输出:

0.0
0.01
0.02
0.03
0.04
0.05
0.060000000000000005
0.07
0.08
0.09
0.09999999999999999
0.10999999999999999
0.11999999999999998

为什么会这样?我们可以采取什么措施来解决这个问题?

这是实数在计算机中的表示方式(Google 浮点运算)的结果。

这个错误并不重要。如果出现这种情况,请适当考虑四舍五入。

或者,使用整数代替,如下所示:

t = 0
dt = 10 # ms
timemax = 120
while(t<timemax):
    print(t)
    t = t + dt
    if(t>= timemax):
        print(f"{t/1000} seconds")
        exit()

如果您实际上不是在对值的连续统一体建模,而是对离散的不同值建模,则后一种方法通常更可取。

Python 的 float 对象使用 64 位,因此它只能表示有限数量的数字。因此,您会看到这些与您对“真实”数学的期望的微小偏差。更多信息请参考this question.

如果您需要精确表示十进制值,可以使用标准库中的 decimal 模块。

还有 mpmath 项目,它允许进行任意精度的浮点运算。