【问题标题】:why does decrementing by 0.1 within for loop produce this undesired result in lua [duplicate]为什么在for循环中减少0.1会在lua中产生这种不希望的结果[重复]
【发布时间】:2021-02-22 17:52:32
【问题描述】:
j=1
for i=1,10 do 
    j=j-0.1
    print(j)
end

输出为:

0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 1.3877787807814e-16

最后一个条目应该是 0 注意:0.1-0.1 返回 0.0 但是,从 j>=0.3 重复执行 j=j-0.1 会产生这个结果

【问题讨论】:

    标签: lua


    【解决方案1】:

    lua 中的数字是双精度数,即Double-precision floating-point format,浮点数是floating precision error。事实上0.1 并不完全是0.1,它是0.1 最接近的表示。

    可能的解决方法是使用整数或带有单独小数部分的整数。 与答案相关的问题:C++ How to avoid floating-point arithmetic error

    【讨论】:

      【解决方案2】:

      四舍五入错误!

      0.1 不能用 IEEE 64 位浮点数精确表示 1/10 在二进制中有一个重复的表示!

      【讨论】:

        猜你喜欢
        • 2013-02-19
        • 1970-01-01
        • 1970-01-01
        • 2015-06-28
        • 2022-01-24
        • 1970-01-01
        • 2023-04-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多