A blog about 3DGS, Nerds and a lot of other stuff

Modulo – The Mystery Operator

January 5th, 2009 Michael Schwarz and categorized as 3DGS, Tutorials

Well, most people – mainly beginners – are very confused about what this “%” or “Modulo” operator does. Well simply put, it returns the “remainder” of a division. Let’s take a look at some easy-to-understand examples:

Let’s do something simple:

4 / 2 = 2 – Rest: 0

We all know how to do this, 2 fits two times into 4, nothing remains and thus rest is = 0.
The modulo operation to get this “0” would be

var rest = 4 % 2;

Now let’s actually take it into account with something that gives us some “rest”:

5 / 2 = 2.5; Rest: 1

Okay, stop now. That doesn’t make sense. Right?! 2.5 times 2 is 5, there is nothing left over!? Well no. If you make a modulo operation, it is as if you make the division with integer numbers. In this case this means:

5 / 2 = 4; Rest 1

Because as an integer number, 2 only fits two times inside 5. And the remainder of the operation is 1, the number it takes to make the full 5.

And again, in modulo this is:

var rest = 5 % 2; // = 1

One more example before I go into “real-life-application” examples:

8 / 3 = 2.666~; Rest: 2 – Or in Modulo result:

8 / 3 = 2; Rest: 2

Okay, let’s make this a real life example. For instance, a simple function that tell us if the a number is odd or even:

function IsEven(num)
{
    return !(num % 2);
}

This is easy explained. The function calculates the modulo for the division “num/2” if the number is even, the result will be 0. As the function is called “IsEven” I invert the result (using !) so that instead of 0 it returns 1. If the function would be called “IsOdd” you can leave it without the !, like this:

function IsOdd(num)
{
    return (num % 2);
}

We can even use it in a clever way to execute something every n’th frame:

...
while(1)
{
    if(total_frames % 5 == 0) // every 5 frames
    {
        temp += 1; // add 1 to temp
    }
    wait(1);
}
...

Modulo is a great way to do counters and do lots of tricky operations in just a matter of a single line. If you know how to use it, modulo is a mighty operator and can optimize your code BIG TIME.

This article has been read 225 times

No Comments

Author (Required)

Mail (Will not be published) (But required anyway)

Website (Woo, optional!)