Matt Sweetman

Latest articles

Modulo and the negative divisor

Turns out the modulo operator % has been hiding a secret from me all these years: it works differently in other languages. I primarily code in Actionscript and Javascript, which both treat modulo the same, but while porting a utility to Python I discovered my code was producing weird results.

The explanation is that modulo can either return a positive or negative result. In Actionscript and Javascript the result has the same sign as the right-hand number (the divisor), but in Python the result has the same sign as the left-hand number (divisor). The choice is up to the authors of the language. There's a wikipedia article on the modulo operation that explains it in more detail, and has a list of languages and their implementation.

If you need to retain the sign of the divisor in Actionscript or Javascript (i.e. the reverse of their default implementation) then here's a method to help you:

function pmod(a, b) {
    return a - (b * Math.floor(a/b));

console.log(100 % -30); // output: 10
console.log(pmod(100, -30)); // output: -20