无法将计算数字与标识数进行比较?

Unable to compare calculated number with idential number?

提问人:cj- 提问时间:6/20/2019 更新时间:6/21/2019 访问量:66

问:

我正在研究一个向量类。在测试向量类时,我在将单位向量的大小与 1 进行比较时遇到了一个失败的测试用例。

在比较它们时,它们似乎都是 ,那么是什么原因导致此测试失败呢?1

我已经尽可能多地删减了问题的根源。我可以将数字转换为字符串并进行比较,但这只会修复测试用例,让问题在以后再次出现。 我正在使用 Lua 5.1 解释器(以确定根本原因),与 LuaRocks 捆绑在一起。

local v = 0.70710678118655^2 + 0.70710678118655^2
print(v, v == 1)

v == 1应该是 ,而不是 。truefalse

Lua Luarocks(卢阿·卢阿洛克斯酒店)

评论

0赞 aschepler 6/20/2019
相关新闻: 浮点数学坏了吗?
1赞 cj- 6/20/2019
我不认为这是一个浮点错误,因为它仍然将两个数字都显示为 .如果剩余的数字足够小,它会不会显示它们?1

答:

0赞 Dirk Horsten 6/20/2019 #1

当然,这是对浮点数学是否损坏的检查。

更多解释:执行此代码

local half = 0.50
local doubleHalf = half + half
if doubleHalf == 1 then
    print('doubleHalf is one')
else
    print('doubleHalf differs '.. doubleHalf - 1 ..'from one')
end
--> doubleHalf is one

local rootHalf = math.sqrt(half)
print('rootHalf is a '.. type(rootHalf) ..' with value', rootHalf)
--> rootHalf is a number with value    0.70710678118654

local square = rootHalf^2 
print('square is a '.. type(square) ..' with value', square)
--> square is a number with value    0.5

if square == half then
    print('square is half')
else
    print('square differs '.. square - half ..' from half')
end
--> square differs 1.110223E-16 from half

vector_length = square + square
if vector_length == 1 then
    print('vector length is one')
else
    print('vector length differs '.. vector_length - 1 ..' from one')
end
--> vector length differs 2.220446E-16 from one

任何使用值的计算机都将以有限的精度进行计算。

1赞 luther 6/21/2019 #2

当将浮点数转换为字符串时,Lua 四舍五入到只有 15 位有效数字。尝试将其设置为 17 位数字以获得准确的表示。

local v = 0.70710678118655^2 + 0.70710678118655^2
print(("%.17g"):format(v), v == 1)

输出:

1.0000000000000071  false