From 883f4d953251dd6de204a4b5f96eaa24e3a72808 Mon Sep 17 00:00:00 2001 From: Anurag Bhat <90216905+faze-geek@users.noreply.github.com> Date: Sat, 2 Mar 2024 12:04:05 +0530 Subject: [PATCH] Add Division operation for complex number in Cmath (#220) * Add __truediv__() for cmath * Some changes * Remove separate zero division case checks * Test all binary operators * Use is_close --- python/cmath.py | 10 ++++++++++ tests/10_cmath.py | 11 +++++++++++ 2 files changed, 21 insertions(+) diff --git a/python/cmath.py b/python/cmath.py index 68e3c1e9..1d796d82 100644 --- a/python/cmath.py +++ b/python/cmath.py @@ -65,6 +65,16 @@ 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): + 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)), diff --git a/tests/10_cmath.py b/tests/10_cmath.py index fd42034d..515c0b50 100644 --- a/tests/10_cmath.py +++ b/tests/10_cmath.py @@ -1,6 +1,17 @@ from cmath import isclose, sqrt, nan, inf, nanj, infj, log import math +c1 = complex(3, 4) +c2 = complex(2, 4.5) + +assert isclose(c1 + 5, complex(8, 4)) +assert isclose(c1 + c2, complex(5, 8.5)) +assert isclose(c1 - c2, complex(1, -0.5)) +assert isclose(c1*4, complex(12, 16)) +assert isclose(c1*c2, complex(-12, 21.5)) +assert isclose(c2/c1, complex(0.96, 0.22)) +assert isclose(c2**2, complex(-16.25, 17.99999999999999)) + assert 1+2j == complex(1, 2) == 2j+1 assert isclose(1+2j + 3+4j, 4+6j)