Modulo with negative operands

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Modulo with negative operands

Albert Chan
I was reading old posts about modulo, http://lua-users.org/lists/lua-l/2017-02/msg00097.html

Does anyone write Lua code that uses % negative divisor behavior ?

If we really need a minus sign, It seems better to explicitly say it.

floor-mod: 1000 % -71 rewrite as -(1000 % 71)

It may be better if % always return non-negative value, Euclidean way.
So, above situation with an unknown n divisor, we can write -(1000 % n)

Regarding the C behavior of fmod() returning sign of dividend,
there is an advantage that other mod does not have ... accuracy.

Example, fmod(-1, 1e100) = -1

With floor-mod or euclidean-mod, we get result rounded to 1e100
Since it is a modulo, that is same as 0, losing all significant digits.
Reply | Threaded
Open this post in threaded view
|

Re: Modulo with negative operands

Dirk Laurie-2
Op Ma. 22 Apr. 2019 om 14:11 het Albert Chan <[hidden email]> geskryf:

> Does anyone write Lua code that uses % negative divisor behavior ?
>
> If we really need a minus sign, It seems better to explicitly say it.

The manual for Lua 5.3 says:

Floor division (//) is a division that rounds the quotient towards
minus infinity, that is, the floor of the division of its operands.
Modulo is defined as the remainder of a division that rounds the
quotient towards minus infinity (floor division).

I.e. % and // are locked together so that a == b*(a//b)+a%b

Previous versions of Lua did not have //, and the discussiion of % was
accordingly longer and may have been confusing to some readers.

It's quite simple now: the result of a%b always lies in the half-open
range from 0 to b, up or down, with b not included.