Just in case someone else finds it useful: Here is a small implementation on how to do a proper *modulo operation in C#* and how to *calculate the modular distance between two numbers*.

If you haven’t been aware, the % operator in most programming languages isn’t the exact equivalent to an arithmetic modulo. In fact, it is simply the remainder of the division between two numbers. Modular arithmetic is a little bit more.

One useful application for the modulo is the modular distance. The modular distance is the distance of two member in a circular space, or a ring. Roughly, it can be understood as the minimum difference between two numbers in this circular space, either going “clockwise” or “counter-clockwise”. For example, in a circle, the *modular distance* between 1° and 359° is 2° (and not 358°).

### Code

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public static class Math { // Calculates x in modulo m public static int Mod(int x, int m) { if (m < 0) m = -m; int r = x % m; return r < 0 ? r + m : r; } // Calculates the distance from a to b in modulo m public static int ModularDistance(int a, int b, int m) { return System.Math.Min(Mod(a - b, m), Mod(b - a, m)); } } |

As a footnote, there wasn’t much information about the modular distance in Wikipedia. Maybe this is better known as something else? I couldn’t find a proper definition in both MathWorld or Wikipedia.

I found this page by guidance of the google gods.

In the meantime I came up with another way that doesn’t require the min-function. Only Arithmetics:

public static int ModularDistance(int a, int b, int m)

{

return System.Math.Abs(m/2 – Mod((3*m)/2+a-b, m));

}

This will return the result which is guaranteed to be 0 <= result <= m/2 as long as 0 <= a <= m and 0 <= b <= m .

The basic idea is to shift both numbers so that one is located at m/2 then you can take the difference without any wrapping issues.

This comment has been removed by the author.

+1 thanks for this, *op and first comment,* works great in Matlab using built-in mod(), as far as I can tell.

Thanks, very useful!

Nice and crisp. Since I needed distance in both directions I didn’t have to use the mins anyway.

very good and nice pics with great information

websphere Online Training

Thank you, sir, I recently came across your blog and have been reading along. nice explanation. It is more effective and interest for new learners. I thought I would leave my first comment. I feel great after reading this information