Modulo
From Tech Artists Wiki
Contents |
[edit] What it is
The modulo operator (usually represented with the percent sign) is a basic mathematical operator that comes in extremely handy in a variety of situations. People are often a bit confused by it at first, but it's actually really simple.
To understand modulo, think back to when you were really little and learning about division for the first time. Before you knew about fractions or decimals, dividing numbers meant coming up with a two-part answer- the answer itself, and the remainder. Modulo gives you that remainder.
So...
10 % 3 = 1 (since there's a remainder of 1 when dividing 10 by 3) 52 % 5 = 2 19 % 10= 9 ...and so on
That's pretty much it. One good way to think of the modulo operator is that it converts a linear progression into a cycle.
| X | X % 5 |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 0 |
| 6 | 1 |
| 7 | 2 |
| 8 | 3 |
| 9 | 4 |
| 10 | 0 |
| 11 | 1 |
| 12 | 2 |
| 13 | 3 |
| 14 | 4 |
| 15 | 0 |
| 16 | 1 |
| 17 | 2 |
| 18 | 3 |
| 19 | 4 |
See? As X continually increases, X % 5 loops through 0 - 4 endlessly.
[edit] Why its useful
Okay, so there's this other mathematical operator. So what?
Well, it tends to be really handy for a lot of things. Here are some examples...
[edit] Iterating over arrays
Let's say that you want to cycle through values in an array. The first time through, you use the item at index 0. Each time thereafter, you add one to the index. That works fine until you reach the end of the array. If you try to use an index that's out-of-bounds, various bad things can happen (the specifics depend on your language, but they're never good). You could use an if statement to check, as in (the below is in MEL syntax):
// assuming an array of 5 elements
if ($myIndex > 4)
{
$myIndex = 0;
}
doSomethingCool($myArray[$myIndex]);
That works just fine, but using the modulo operator leads to cleaner code, as in:
doSomethingCool($myArray[$myIndex % 5]);
In the above, if it so happened that $myIndex was pointing beyond the end of the array (greater than 4 in this case, since array indices start at 0), it would wrap around back to 0. So, as $myIndex increases in size, it continually cycles through the 5 elements in $myArray.
