3

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.

Georgy
  • 12,464
  • 7
  • 65
  • 73
Evelyn
  • 85
  • 8
  • It works different with complex numbers, and even still, the real part should not be minus 1. This explains what I am try to do https://www.quora.com/How-do-I-find-Modulo-of-complex-numbers – Evelyn Feb 06 '19 at 12:33
  • According to [WolframAlpha](https://www.wolframalpha.com/input/?i=(8%2B2i)%25(2%2B1i)) you get correct output. – Georgy Feb 06 '19 at 13:49
  • 1
    Is this actually useful somewhere? Is it worth adding this to Python? – norok2 Feb 06 '19 at 14:59
  • yes, it is useful and worth adding, although the uses for it are somewhat obscure, its worth it in my opinion given how simple it is. – Evelyn Feb 06 '19 at 16:07

1 Answers1

1

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.

norok2
  • 25,683
  • 4
  • 73
  • 99