Skip to content

Instantly share code, notes, and snippets.

@MLWhiz
Created November 28, 2020 19:08
Show Gist options
  • Save MLWhiz/6ebd71117dab16599fc83e604e7cdb9d to your computer and use it in GitHub Desktop.
Save MLWhiz/6ebd71117dab16599fc83e604e7cdb9d to your computer and use it in GitHub Desktop.
import math
class Complex:
def __init__(self, re=0, im=0):
self.re = re
self.im = im
def __add__(self, other):
if isinstance(other, int) or isinstance(other, float):
return Complex(self.re + other,self.im)
elif isinstance(other, Complex):
return Complex(self.re + other.re , self.im + other.im)
else:
raise TypeError
def __sub__(self, other):
if isinstance(other, int) or isinstance(other, float):
return Complex(self.re - other,self.im)
elif isinstance(other, Complex):
return Complex(self.re - other.re, self.im - other.im)
else:
raise TypeError
def __mul__(self, other):
if isinstance(other, int) or isinstance(other, float):
return Complex(self.re * other, self.im * other)
elif isinstance(other, Complex):
# (a+bi)*(c+di) = ac + adi +bic -bd
return Complex(self.re * other.re - self.im * other.im,
self.re * other.im + self.im * other.re)
else:
raise TypeError
def __truediv__(self, other):
if isinstance(other, int) or isinstance(other, float):
return Complex(self.re / other, self.im / other)
elif isinstance(other, Complex):
x = other.re
y = other.im
u = self.re
v = self.im
repart = 1/(x**2+y**2)*(u*x + v*y)
impart = 1/(x**2+y**2)*(v*x - u*y)
return Complex(repart,impart)
else:
raise TypeError
def value(self):
return math.sqrt(self.re**2 + self.im**2)
def __eq__(self, other):
if isinstance(other, int) or isinstance(other, float):
return self.value() == other
elif isinstance(other, Complex):
return self.value() == other.value()
else:
raise TypeError
def __lt__(self, other):
if isinstance(other, int) or isinstance(other, float):
return self.value() < other
elif isinstance(other, Complex):
return self.value() < other.value()
else:
raise TypeError
def __gt__(self, other):
if isinstance(other, int) or isinstance(other, float):
return self.value() > other
elif isinstance(other, Complex):
return self.value() > other.value()
else:
raise TypeError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment