Reputation: 321
I am trying to replicate the behavior of Math.IEEERemainder (in C#) in Lua. I know that I can always write the entire thing from scratch, but I am trying to avoid it if there is something built-in.
I have tried the % operator and math.fmod. None of them behave the same.
For instance:
Math.IEEERemainder(3.0,2.0) //-1
(3.0%2.0) --1
math.fmod(3.0,2.0) --1
Upvotes: 1
Views: 66
Reputation: 974
function IEEERemainder(x, y)
y = y + 0.0
local q1 = math.floor(x/y)
local q2 = math.ceil(x/y)
local r1 = x - y * q1
local r2 = x - y * q2
local d1 = math.abs(r1)
local d2 = math.abs(r2)
local r = (d1 < d2 or d1 == d2 and q1 % 2 == 0) and r1 or r2
return r == 0 and x < 0 and -r or r
end
Upvotes: 1