Ruby Modulo 3 with Negative Numbers Is Unintuitive

Real, mathematical modulo operation in Postgres?


SELECT MOD(24 + MOD(-2, 24), 24);

will return 22 instead of -2

integer division in Ruby with negative value

This is how it is designed. Ruby rounds numbers towards negative infinity in case of negative division and modulo operation. This is not unique to Ruby, Python and Perl behaves like that also.

However, this approach provides a good mathematical reason.

a / b = q with remainder r

such that

b * q + r = a and 0 <= r < b

From what I read, this is how arithmetic is taught in Japan.

Edit:

sawa pointed out that this is how positive arithmetic is taught in Japan, not negative numbers. However, as he said, this can be extended to negative numbers as well.

Sources:

Ruby Forums

Mod with negative numbers gives a negative result in Java and C

The % operator is treated as a remainder operator, so the sign of the result is the same as that of the dividend.

If you want a modulo function, you can do something like this:

int mod(int a, int b)
{
int ret = a % b;
if (ret < 0)
ret += b;
return ret;
}


Related Topics



Leave a reply



Submit