Be careful, % != mod

Just an FYI for folks if you want to use modular arithmetic for traversing loops. The % operator is not the same as the mod operator. a%b just gives the remainder of a/b. For positive a this is the same as the mod operator. However if a is negative then a%b is not the same as the mod operator.

Here is a general mod function that can handle both positive and negative values (I got it from a number theory text)

private int mod(int a, int b) {
    return (int)(a - b * Mathf.Floor((float)a/(float)b));
}

I found I needed this because I wanted to give my NPCs the option of traversing a loop “clockwise” (in order of increasing child index) or “counter clockwise” (in order of decreasing child index). So I have the two following methods for getting the next or previous index

public int GetNextIndex(int idx) {
     return mod(idx + 1, transform.childCount);
}

public int GetPreviousIndex(int idx) {
     return mod(idx - 1, transform.childCount);
 }
3 Likes

Yes, this is an issue that has plagued most computer languages since the beginning. % is called the Modulo operator, but would be more accurately named the remainder operator. It’s always been a bit wonky in the negative range.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms