无法比较计算数与相同数?

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

当比较它们时,它们都显示为1,那么是什么原因导致此测试失败?

我已经尽可能简化了它们,以便找到问题的根本原因。我可以将数字强制转换为字符串并进行比较,但这只能解决测试用例,使问题在以后的时间里再次出现。 我使用的是Lua 5.1解释器(以识别根本原因),它与LuaRocks捆绑在一起。

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

v == 1应该为true,而不是false

点赞
用户4385647
用户4385647

当然,这是一个“浮点数运算失效”问题的例子。

更多解释:执行这段代码

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

任何使用数值的计算机都会有限精度计算。

2019-06-20 11:40:52
用户3574628
用户3574628

当将一个浮点数转换为字符串时,Lua只保留了15个有效数字。尝试使用17个数字以获得精确表示。

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

输出:

1.0000000000000071  false
2019-06-20 21:25:59