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
This commit is contained in:
Anurag Bhat 2024-03-02 12:04:05 +05:30 committed by GitHub
parent e82cad5b25
commit 883f4d9532
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 21 additions and 0 deletions

View File

@ -65,6 +65,16 @@ class complex:
def __rmul__(self, other): def __rmul__(self, other):
return self.__mul__(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): def __pow__(self, other: int | float):
if type(other) in (int, float): if type(other) in (int, float):
return complex(self.__abs__() ** other * math.cos(other * phase(self)), return complex(self.__abs__() ** other * math.cos(other * phase(self)),

View File

@ -1,6 +1,17 @@
from cmath import isclose, sqrt, nan, inf, nanj, infj, log from cmath import isclose, sqrt, nan, inf, nanj, infj, log
import math 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 1+2j == complex(1, 2) == 2j+1
assert isclose(1+2j + 3+4j, 4+6j) assert isclose(1+2j + 3+4j, 4+6j)