Modulo and Modular Distance in C#

CLOK-5076

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.

6 Comments

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

Leave a Reply

Your email address will not be published. Required fields are marked *