Wednesday, October 28, 2015

Code: Normalize overflowing values

To normalize values like degrees where the main range is [0, 360) but all other values are accepted too the obvious is:

value = value % 360

Which  in case of a [min, max) range is:

value = (value - min) % (max - min) + min

But when the value is a negative number or even smaller than the min we get wrong result.
What we can do is "overflow" the value one more time:

value = ((value % 360) + 360) % 360

Which  in case of our generic [min, max) range is:

value = ((value - min) % (max - min) + max - min) % (max - min) + min

In an extended form:

len = max - min
value = ((value - min) % len + len) % len + min


done_