n Mod -m: Max vs. Matlab

Today I was working on a little acoustics simulation patcher in Cycling 74’s Max, and part of the code required the use of a modulo function. No problem, right?

Problem. I originally wrote the code in Matlab, and I was porting it to Max; and the numbers just weren’t working properly. After getting rid of my own home-made bugs, it still wasn’t working…

Turns out that there seems to be a disagreement in the code community about how to do the modulo of a negative number.

The best indication of the problem I was facing is found on this page, where you can see that different languages come up with different answers for -13 mod 3 and 13 mod -3. The problem is that neither Max nor Matlab are in the list. So: here are the results of those two, to add to the list.

Matlab’s results
Max’s results, including using the gen object.

The results are:

Language13 mod 3-13 mod 313 mod -3-13 mod -13

This means that Matlab behaves like Python, using the formula

mod(a, n) = a – n * floor(a / n)

whereas Max behaves like C and Java.

So, if you, like me, move back and forth between Matlab and Max, beware!