# Modulo and Modular Distance in C#

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

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.

1. Lorenz Quack says:

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.

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

2. Jeff Trent says:

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

3. 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