First of all, the % operator is the “remainder” operator in both Unreal Engine and Unity, rather than the “modulo” operator. It does not correct for negative values, so you are not guaranteed to return non-negative values with only the % operator.
There are some different formulas being posted here. I set up a test for a few different values (Unreal Engine and Unity turned out to be equivalent in these tests):
**If we define our desired behavior to be “wrapping around an interval” (going from 0 to the divisor; 10 in the following examples), then the following equations should hold: **
- 3 % 10 = 3
- (-3) % 10 = 7
- 13 % 10 = 3
- (-3) % (-10) = ?
Regarding the last point here, most formulas seem to yield the same sign as the divisor, regardless of mathematical meaning, so I’ll leave that fringe case open for interpretation.
I will refer to the variations of the values in this table as ++, ±, -+, and --, mapping to the sign of the a and b variables, respectively. I.e. the dividend is the former of these symbols, and the divisor is the latter. E.g. if a = 3 and b = (-10), then their shorthand symbols would be “±”.
b - Abs(a % b)
- Relatively cheap to use; only one [%], one [-], and one [Abs].
- Overcorrects with “++”.
- Correct with “-+”.
- Overshoots with “–”.
- Overshoots with “±”.
- **Good for correcting for negative dividents, but nothing more. **
(a % b + b) % b
- Relatively expensive to use; two [%] and one [+].
- Correct with “++”.
- Correct with “-+”.
- “–” mirrors behavior of “++”.
- “±” mirrors behavior of “-+”.
- **Safest option, but expensive. **
a % b + b
- Cheapest to use; only one [%] and one [+].
- Overcorrects with “++”.
- Correct with “-+”.
- “–” mirrors behavior of “++”.
- “±” mirrors behavior of “-+”.
- **Most performant on “-+”, but incorrect with like-signed configurations (“++” or “–”). **
TL;DR
- Use this formula to be safe in all cases: “(a % b + b) % b”
- Use this formula to be safe if divisor is positive: “b - Abs(a % b)”
- In the formulas discussed, the result will have same sign as the divisor (bottom part of the fraction).
- **Stay away from negative divisors if you can. **
