Reputation: 13672
According to Wikipedia, the modulo operator (remainder of integer division) on n
should yield a result between 0
and n-1
.
This is indeed the case in python
:
print(-1%5) # outputs 4
In Ruby
:
puts -1%5 # outputs 4
In Haskell
main = putStrLn $ show $ mod (-1) 5
But inJavascript
:
console.log(-1%5);
The result is -1
!!
Why is that ? is there logic behind this design decision ?
While -1
is equivalent to 4
modulo 5
, negative values makes it harder to use as indices.
For example:
arr[x%5]
would always be a valid expression in python
and Ruby
when the array length is more than 5
, but in the Javascript
, this is an exception waiting to happen.
Upvotes: 1
Views: 1388
Reputation: 56
Note that while in most languages, ‘%’ is a remainder operator, in some (e.g. Python, Perl) it is a modulo operator. For two values of the same sign, the two are equivalent, but when the dividend and divisor are of different signs, they give different results. To obtain a modulo in JavaScript, in place of a % n, use ((a % n ) + n ) % n
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder
Upvotes: 1
Reputation: 664164
If by "modulus" you understand the remainder of the Euclidean division as common in mathematics, the %
operator is not the modulo operator. It rather is called the remainder operator, whose result always has the same sign as the dividend. (In Haskell, the rem
function does this).
This behaviour is pretty common amongst programming languages, notably also in C and Java from which the arithmetic conventions of JavaScript were inspired.
Upvotes: 2