-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplex.py
More file actions
104 lines (94 loc) · 2.97 KB
/
complex.py
File metadata and controls
104 lines (94 loc) · 2.97 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
class complx:
def __init__(self, a, b):
self.a = a
self.b = b
def __pos__(self): return self
def __neg__(self): return 0-self
def __add__(self, y): return plus(self, y)
def __radd__(self, x): return plus(x, self)
def __sub__(self, y): return minus(self, y)
def __rsub__(self, x): return minus(x, self)
def __mul__(self, y): return times(self, y)
def __rmul__(self, x): return times(x, self)
def __div__(self, y): return divide(self, y)
def __rdiv__(self, x): return divide(x, self)
def __truediv__(self, y): return divide(self, y)
def __rtruediv__(self, x): return divide(x, self)
def __eq__(self, x): return eq(self, x)
def __ne__(self, x): return not eq(self, x)
def __repr__(self): return complx_to_str(self)
def real_part(x):
if isinstance(x, complx): return x.a
else: return x
def imag_part(x):
if isinstance(x, complx): return x.b
else: return 0
def lift(x):
if isinstance(x, complx): return x
else: return complx(x, 0)
def plus(x, y):
if isinstance(x, complx):
if isinstance(y, complx):
a = real_part(x)
b = imag_part(x)
c = real_part(y)
d = imag_part(y)
return complx(a+c, b+d)
else: return x+lift(y)
else:
if isinstance(y, complx): return lift(x)+y
else: return x+y
def minus(x, y):
if isinstance(x, complx):
if isinstance(y, complx):
a = real_part(x)
b = imag_part(x)
c = real_part(y)
d = imag_part(y)
return complx(a-c, b-d)
else: return x-lift(y)
else:
if isinstance(y, complx): return lift(x)-y
else: return x-y
def times(x, y):
if isinstance(x, complx):
if isinstance(y, complx):
a = real_part(x)
b = imag_part(x)
c = real_part(y)
d = imag_part(y)
return complx(a*c-b*d, a*d+b*c)
else: return x*lift(y)
else:
if isinstance(y, complx): return lift(x)*y
else: return x*y
# (a+bi)/(c+di)
# =((a+bi)(c-di))/((c+di)(c-di))
# =((a+bi)(c-di))/(c^2-d^2)
# =((ac+bd)/(c^2-d^2))+((bc-ad)/(c^2-d^2))i
def divide(x, y):
if isinstance(x, complx):
if isinstance(y, complx):
a = real_part(x)
b = imag_part(x)
c = real_part(y)
d = imag_part(y)
return complx((a*c+b*d)/(c*c-d*d), (b*c-a*d)/(c*c-d*d))
else: return x/lift(y)
else:
if isinstance(y, complx): return lift(x)/y
else: return x/y
def eq(x, y):
if isinstance(x, complx):
if isinstance(y, complx):
a = real_part(x)
b = imag_part(x)
c = real_part(y)
d = imag_part(y)
return a==c and b==d
else: return x==lift(y)
else:
if isinstance(y, complx): return lift(x)==y
else: return x==y
def complx_to_str(x):
return "complx(%s, %s)"%(str(real_part(x)), str(imag_part(x)))