如果 lua number 是 double,=/<=/>= 操作总是正确的吗? [英] if lua number is double, does =/<=/>= operations always correct?

查看:21
本文介绍了如果 lua number 是 double,=/<=/>= 操作总是正确的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所知,浮点数有一个精度问题,即值 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++,并将这个值存储在一个双变量中,一段时间后,我将值 (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

没有.

一个 64 位的 double 可以比一个 32 位的整数精确地保存更多的整数值.

A 64 bit double can hold many more integer values precisely than a 32 bit integer.

这篇关于如果 lua number 是 double,=/&lt;=/&gt;= 操作总是正确的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆