Seeing how Python has a support for a lot of different mathematical operations for complex numbers, I’m surprised that there is no support for modular arithmetic with complex numbers, that is z % w for z,w\in\mathbb C.
Sure, modular arithmetic for complex numbers is a bit obscure of a topic, however I don’t really see why it shouldn’t be implemented given how simple it is.
Actually I have my own implementation of it using a class method:
# Minimum reproducible example. Here I use `i` as the complex unit
# and also only use 2 decimal places of precision, which seems to
# be enough to get correct values.
class Complex(object):
def __init__(self, real, imag):
self.r = real
self.i = imag
def __sub__(self, num):
real = self.r - num.r
imag = self.i - num.i
return Complex(real, imag)
def __mul__(self, num):
real = self.r * num.r - self.i * num.i
imag = self.r * num.i + self.i * num.r
return Complex(real, imag)
def __truediv__(self,num):
try:
x, y, z = self.r * num.r + self.i * num.i, \
self.i * num.r - self.r * num.i, \
num.r ** 2 + num.i ** 2
real = x / z
imag = y / z
return Complex(real, imag)
except ZeroDivisionError as ZDE:
return ZDE
def __round__(self):
real = (self.r + 0.5) - ((self.r + 0.5) % 1.0)
imag = (self.i + 0.5) - ((self.i + 0.5) % 1.0)
return Complex(real, imag)
def __mod__(self, modu):
# We can define for two complex numbers `z = a + b*i` and `w = c + d*i`
# z % w = z - w*round(z / w). Note that the correct formula actually
# uses `floor` and not `round` but it doesn't seem to work correctly
# if I change the method to `floor` here in Python.
return self - ((self / modu).__round__() * modu)
def __str__(self):
if self.i >= 0:
res = "%.2f+%.2fi" % (self.r, self.i)
else:
res = "%.2f-%.2fi" % (self.r, abs(self.i))
return res
# Examples: (verified with Wolfram Alpha)
# print(Complex(0.06, 9.03) % Complex(1.02, 13.01)) # -0.96-3.98i
# print(Complex(1, 2) % Complex(1, 3)) # 0.00-1.00i
# print(Complex(5107, 607) % Complex(23, 27)) # -4.00+22.00i
# print(Complex(503.03, 6.56) % Complex(23.1,27.09)) # -2.59+16.85i
# print(Complex(4, 0) % Complex(0, 1)) # 0.00+0.00i
So it seems like it could be implemented easily enough, but if this hasn’t already been implemented in Python then there must be some other reason why it currently isn’t, and that I wonder why.