-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComplex.py
More file actions
51 lines (44 loc) · 1.34 KB
/
Complex.py
File metadata and controls
51 lines (44 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Complex:
def __init__(self, real=0, imaginary=0):
self.real = real
self.imaginary = imaginary
def __str__(self):
return '{} + i*{}'.format(self.real, self.imaginary)
def __add__(self, obj):
res = Complex()
if type(obj) == type(self):
res.real = obj.real + self.real
res.imaginary = obj.imaginary + self.imaginary
else:
res.real = self.real + obj
res.imaginary = self.imaginary
return res
def __sub__(self, obj):
res = Complex()
if type(obj) == type(self):
res.real = obj.real - self.real
res.imaginary = obj.imaginary + self.imaginary
else:
res.real = self.real - obj
res.imaginary = self.imaginary
return res
def __mul__(self, obj):
res = Complex()
if type(obj) == type(self):
res.real = self.real * obj.real - obj.imaginary*obj.imaginary
res. imaginary = self.real*self.imaginary + obj.real*self.imaginary
else:
res.real = self.real * obj
res.imaginary = self.imaginary * obj
return res
def __truediv__(self, obj):
res = Complex()
if type(obj) == type(self):
obj1 = Complex(obj.real, - obj.imaginary)
obj1.real /= obj.real ** 2 + obj.imaginary ** 2
obj1.imaginary /= obj.real ** 2 + obj.imaginary ** 2
res = obj1
else:
res.real = self.real / obj
res.imaginary = self.imaginary / obj
return res