如果lua数是双数,=/< =/>操作是否总是正确? [英] if lua number is double, does =/<=/>= operations always correct?
问题描述
如您所知,浮点数存在精度问题,即值1将为0.9999999.lua在C中使用==来检查两个双数是否相等.所以问题是:
As you know, float point has a precision problem, that is a value 1 will be 0.9999999. And lua use == in C to check whether two double numbers equal. So the problem is:
a = 5.6
b = 14 * 0.4
print(a==b) ; => false
但更糟糕的是:
a = 1
...
if a < 1 then print("<1") end ; => sometimes a < 1
那么我该如何避免呢?我签出了lua源代码,看来我可以在luaconf.h中修改luai_numeq/luai_numle)宏,但这是必需的吗?
So how can i avoid this ? I check out lua source code, it seems i can modify luai_numeq/luai_numle) macros in luaconf.h, but is this necessary ?
更新
第二个例子并不正确.实际上,我的问题是,我将值1传递给使用lua_tonumber来获取值的c/c ++,并将此值存储在double变量中,并在一段时间后将值(lua_pushnumber)推入lua,并且将<1发生了:
The second example is not really correct. Actually my problem is, I pass a value 1 to c/c++ which use lua_tonumber to get the value, and i store this value in a double variable, and after sometime, I push the value (lua_pushnumber) to lua, and a < 1 happened:
in lua:
my_cfunction(1)
...
in c:
int my_cfunction(lua_State *L) {
double val = lua_tonumber(L, 1);
...
...
lua_pushnumber(L, val);
in lua:
local a = my_cfunction2()
if a < 1 then ... end
推荐答案
浮点数存在精度问题
float point has a precision problem
与32位整数相比,64位double可以容纳更多的整数值.
A 64 bit double can hold many more integer values precisely than a 32 bit integer.
这篇关于如果lua数是双数,=/< =/>操作是否总是正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!