From 6b802569294c4229aa8374646b2a01d00186b84d Mon Sep 17 00:00:00 2001 From: faze-geek Date: Fri, 1 Mar 2024 17:49:39 +0530 Subject: [PATCH] Add __truediv__() for cmath --- python/cmath.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/python/cmath.py b/python/cmath.py index 68e3c1e9..a246c5eb 100644 --- a/python/cmath.py +++ b/python/cmath.py @@ -65,6 +65,18 @@ class complex: def __rmul__(self, other): return self.__mul__(other) + def __truediv__(self, other): + if type(other) is complex: + denominator = other.real ** 2 + other.imag ** 2 + real_part = (self.real * other.real + self.imag * other.imag) / denominator + imag_part = (self.imag * other.real - self.real * other.imag) / denominator + return complex(real_part, imag_part) + if type(other) in (int, float): + if other == 0: + raise ZeroDivisionError("Division by zero in complex number division") + return complex(self.real / other, self.imag / other) + return NotImplemented + def __pow__(self, other: int | float): if type(other) in (int, float): return complex(self.__abs__() ** other * math.cos(other * phase(self)),