All of the answers here work great if your divisor is positive, but it's not quite complete. Here is my implementation which always returns on a range of [0, b)
, such that the sign of the output is the same as the sign of the divisor, allowing for negative divisors as the endpoint for the output range.
PosMod(5, 3)
returns 2
PosMod(-5, 3)
returns 1
PosMod(5, -3)
returns -1
PosMod(-5, -3)
returns -2
/// <summary>
/// Performs a canonical Modulus operation, where the output is on the range [0, b).
/// </summary>
public static real_t PosMod(real_t a, real_t b)
{
real_t c = a % b;
if ((c < 0 && b > 0) || (c > 0 && b < 0))
{
c += b;
}
return c;
}
(where real_t
can be any number type)