开发者

math.fmod always euqls math.mod?

I tried to figure out the difference between math.fmod and math.mod with the following code:

a={9.5 ,-9.5,-9.5,9.5}
b={-3.5, 3.5,-3.5,3.5}
for i=1,#a do
    if math.fmod(a[i],b[i])~=math.mod(a[i],b[i]) then
        print("yeah")
    end
end

It never prints "yeah"! What should I put in array a and b to see "yeah"?

The documentation of math.fmod() say that it returns the remainder of the division of x by y that开发者_JAVA百科 rounds the quotient towards zero.


math.mod is the same function as math.fmod. Actually, math.mod exists only for compatibility with previous versions; it's not listed in the manual. Try math.modf instead of math.mod in your code.


Modulo in Lua is defined as "the remainder of a division that rounds the quotient towards minus infinity" -Link here - Which is different from the definition of fmod (as you quoted in your original post).

What you really need to do is use the modulo operator (%) rather than math.mod:

a={9.5 ,-9.5,-9.5,9.5}
b={-3.5, 3.5,-3.5,3.5}
for i=1,#a do
    if math.fmod(a[i],b[i]) ~= a[i] % b[i] then
        print("yeah")
    end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜