mirror of
https://github.com/pocketpy/pocketpy
synced 2025-10-19 19:10:17 +00:00
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:
parent
e82cad5b25
commit
883f4d9532
@ -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)),
|
||||
|
@ -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)
|
||||
|
Loading…
x
Reference in New Issue
Block a user