Die*_* Hu 5 floating-point lua floating-accuracy modulo
我刚刚在Lua使用了modulo(%),我注意到它出于某种原因非常不准确.我在"魔兽世界"中使用它,但我认为它至少在某种程度上是最新的.
无论如何,使用以下示例,输出将为1;
print((0.6/(0.1^(2-1)))%1)
Run Code Online (Sandbox Code Playgroud)
但是当我使用以下内容时,它将返回0;
print((0.6*(10^(2-1)))%1)
Run Code Online (Sandbox Code Playgroud)
就我受过教育而言,0.6/0.1应相当于0.6*10.
这不是一个问题或问题,但我只是对原因感到好奇.在我看来,数学中的不准确性会非常具有破坏性.
如果查看Lua手册,%操作定义为
a % b == a - math.floor(a/b)*b
Run Code Online (Sandbox Code Playgroud)
所以表达
6 - math.floor(6/1) * 1
Run Code Online (Sandbox Code Playgroud)
将等于零.
但是,由于浮点不准确(0.1不存在浮点数,最接近应该是0.1000000014...),这些应该是您的中间结果:
> print(math.floor(0.6*10))
6
> print(math.floor(0.6/.1))
5
Run Code Online (Sandbox Code Playgroud)
所以你得到了
6 - 6 * 1 = 0
6 - 5 * 1 = 1
Run Code Online (Sandbox Code Playgroud)