Search code examples
pythoncomplex-numbersmodular-arithmetic

How to calculate a modulo of complex numbers?


I am trying to find a way to do (w+xi) % (y+zi) in Python.

I have tried cmath but it doesn't seem to have support for this. I have made sure it is mathematically possible and attempted to program it, however it didn't work. The code is below, I found that the issue was sometime after dividing numbers would need to be rounded but at other times this produced an incorrect result.

def ComplexModulo(a,b):
       x = a/b
       x = round(x.real) + (round(x.imag)*1j)
       z = x*b
       return a-z

I need a better way to figure this out, as right now if I do (8+2j)%(2+1j) I should get (1+1j), but I instead get (-1+0j). I tried also changing round to int, and different combinations of that, and although it worked in some instances it failed in others.


Solution

  • The correct definition of the modulo operation involves using floor instead of round. You could find this in either math or numpy packages.

    EDIT

    To expand a bit on why round() and int() do not work, it has to do with the rounding of course.

    Let's consider an integer example:

    5 / 3 = 1.6666...
    5 // 3 = 1
    5 % 3 = 2
    
    5 == 3 * 1 + 2
    

    Now:

    round(5 / 3) == 2 != 5 // 3
    

    which will not give the correct result for the integer quotient of 5 / 3.

    On the other hand:

    int(5 / 3) == 1 == 5 // 3
    

    Would actually give the correct quotient in this case.

    But if now consider:

    -5 / 3 = -1.6666...
    -5 // 3 = -2
    -5 % 3 = 1
    
    -5 == 3 * (-2) + 1
    

    Then:

    int(-5 / 3) == -1 != -5 // 3
    

    and:

    round(-5 / 3) == -2 == -5 // 3
    

    and in this case round() would give the correct result and int() will not.

    floor(), being defined as the largest integer smaller then the input, would work in both scenarios correctly.