73 lines
2.2 KiB
Python
73 lines
2.2 KiB
Python
class Complex:
|
|
def __init__(self, real=0.0, imag=0.0):
|
|
self.real = real
|
|
self.imag = imag
|
|
|
|
def __add__(self, other):
|
|
if isinstance(other, Complex):
|
|
return Complex(self.real + other.real, self.imag + other.imag)
|
|
return NotImplemented
|
|
|
|
def __sub__(self, other):
|
|
if isinstance(other, Complex):
|
|
return Complex(self.real - other.real, self.imag - other.imag)
|
|
return NotImplemented
|
|
|
|
def __mul__(self, other):
|
|
if isinstance(other, Complex):
|
|
return Complex(
|
|
self.real * other.real - self.imag * other.imag,
|
|
self.real * other.imag + self.imag * other.real
|
|
)
|
|
return NotImplemented
|
|
|
|
def __truediv__(self, other):
|
|
if isinstance(other, Complex):
|
|
denom = other.real ** 2 + other.imag ** 2
|
|
if denom == 0:
|
|
raise ZeroDivisionError("division by zero")
|
|
return Complex(
|
|
(self.real * other.real + self.imag * other.imag) / denom,
|
|
(self.imag * other.real - self.real * other.imag) / denom
|
|
)
|
|
return NotImplemented
|
|
|
|
def __str__(self):
|
|
return f"{self.real} + {self.imag}i"
|
|
|
|
def __repr__(self):
|
|
return f"Complex({self.real}, {self.imag})"
|
|
|
|
def conjugate(self):
|
|
return Complex(self.real, -self.imag)
|
|
|
|
def magnitude(self):
|
|
return (self.real ** 2 + self.imag ** 2) ** 0.5
|
|
|
|
def phase(self):
|
|
import math
|
|
return math.atan2(self.imag, self.real)
|
|
|
|
def __eq__(self, other):
|
|
if isinstance(other, Complex):
|
|
return self.real == other.real and self.imag == other.imag
|
|
return NotImplemented
|
|
|
|
def __ne__(self, other):
|
|
return not self.__eq__(other)
|
|
|
|
if __name__ == "__main__":
|
|
c1 = Complex(3, 4)
|
|
c2 = Complex(1, 2)
|
|
|
|
print("c1:", c1)
|
|
print("c2:", c2)
|
|
print("c1 + c2:", c1 + c2)
|
|
print("c1 - c2:", c1 - c2)
|
|
print("c1 * c2:", c1 * c2)
|
|
print("c1 / c2:", c1 / c2)
|
|
print("Conjugate of c1:", c1.conjugate())
|
|
print("Magnitude of c1:", c1.magnitude())
|
|
print("Phase of c1:", c1.phase())
|
|
print("Are c1 and c2 equal?", c1 == c2)
|
|
|