Created
November 28, 2020 18:52
-
-
Save MLWhiz/6fb545b464b9eaf250ea98ef2160c98c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment