Monthly Archives: July 2015

A Practical Replacement for Modulo

wrapx1The modulo operator % is great when everything is positive. But when your input value goes negative, the values it returns can be a big surprise.

For example, suppose you have a car going around a 3-mile racetrack. The position of the car is computed by some complicated program, but you get back a floating-point value I’ll call a that tells you how many miles the car has driven after passing the starting line. Because the car can take some warm-up laps before the race begins, you can also have negative values of a, meaning that you have that much distance to travel before the race begins. But the car is still always on the track, so you still need to turn both positive and negative values of a into positions on the track between 0 and 3.

When a>0, then a % 3 is always a number between 0 and 3, and our work is done. But if a is negative, watch out! The result of -1 % 3 is -1. And -4 % 3 is also -1. And -5 % 3 is -2. Though making modulo work this way gives it some nice formal properties, these results can be a real hassle in practice. Here’s how to fix things up.

Continue reading