Skip to content

Commit

Permalink
python - complex number
Browse files Browse the repository at this point in the history
  • Loading branch information
MrinmoiHossain committed Nov 20, 2018
1 parent b556782 commit 0655373
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions Python/Classes/Classes Dealing with Complex Numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import math

class Complex(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary

def __add__(self, no):
return Complex(self.real + no.real, self.imaginary + no.imaginary)

def __sub__(self, no):
return Complex(self.real - no.real, self.imaginary - no.imaginary)

def __mul__(self, no):
self.r = self.real * no.real - self.imaginary * no.imaginary
self.i = self.real * no.imaginary + self.imaginary * no.real
return Complex(self.r, self.i)

def conj(self):
return Complex(self.real, -self.imaginary)

def __truediv__(self, no):
if no.imaginary == 0:
return Complex(self.real / no.real, self.imaginary / no.real)
else:
return (self *no.conj()) / (no *no.conj())

def mod(self):
return Complex(math.sqrt((self.real**2 + self.imaginary**2)), 0)

def __str__(self):
if self.imaginary == 0:
result = "%.2f+0.00i" % (self.real)
elif self.real == 0:
if self.imaginary >= 0:
result = "0.00+%.2fi" % (self.imaginary)
else:
result = "0.00-%.2fi" % (abs(self.imaginary))
elif self.imaginary > 0:
result = "%.2f+%.2fi" % (self.real, self.imaginary)
else:
result = "%.2f-%.2fi" % (self.real, abs(self.imaginary))
return result

if __name__ == '__main__':
c = map(float, input().split())
d = map(float, input().split())
x = Complex(*c)
y = Complex(*d)
print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n')

0 comments on commit 0655373

Please sign in to comment.