Modulo and the negative divisor
I never had reason to doubt the modulo operator, but it turns out it’s been hiding a little secret from me all these years: it works differently in other programming langauges. I discovered this while converting a Python program to Flash. In Python the result of the modulo operation has the same sign as the right-hand number (divisor), but in Actionscript it has the same sign as the left-hand number (dividend). There’s a wikipedia article on the modulo operation that explains it in more detail, and has a list of languages and their relevant implementation.
If you need to retain the sign of the divisor in your result (i.e. python-style) here’s a quick Actionscript method to achieve it:
{
return a - (b * Math.floor(a/b));
}
trace(100 % -30); // output: 10
trace(mod(100, -30)); // output: -20
Admittedly this is the first time in 10 years of actionscript programming that it’s caused me a problem, so take from that what you will.
Posted: October 24th, 2009 under Actionscript.