-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplex.py
More file actions
136 lines (83 loc) · 2.53 KB
/
Copy pathcomplex.py
File metadata and controls
136 lines (83 loc) · 2.53 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
from math import sqrt, atan, exp, sin, cos, pi
# Building the basic class for complex numbers
class Complex:
def __init__(self, a, b=0):
self.re = a
self.im = b
def __add__(self, other):
# convert real to complex
if isinstance(other, (int, float)):
other = Complex(other)
return Complex(self.re + other.re, self.im + other.im)
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
return Complex(self.re - other.re, self.im - other.im)
def __rsub__(self, other):
if isinstance(other, (int, float)):
other = Complex(other)
return other.__sub__(self)
def __mul__(self, other):
if isinstance(other, (int, float)):
other = Complex(other)
re = (self.re * other.re) - (self.im * other.im)
im = self.re * other.im + self.im * other.re
return Complex(re, im)
def __rmul__(self, other):
return self.__mul__(other)
def __eq__(self, other):
return self.re == other.re and self.im == other.im
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
str = '{} + {}i'.format(self.re, self.im)
return str
def conjugate(self):
return Complex(self.re, -1 * self.im)
def phase(self):
return atan(self.im / self.re)
def to_polar(self):
r = norm(self)
theta = self.phase()
return r, theta
# important basic functions related to complex arithmetic
def norm(z):
return sqrt(z.re ** 2 + z.im ** 2)
def rect(r, theta):
"""
Convert from polar to rectangular coordinates
:param r: radius
:param theta: angle
:return:
"""
re = r * cos(theta)
im = r * sin(theta)
return Complex(re, im)
# implementation of complex-valued functions
def roots(k, z):
"""
Finds the kth roots of a complex number
:param k: int
:param z: complex
:return: list of roots in polar coordinates
"""
if isinstance(z, (int, float)):
z = Complex(z)
r, theta = z.to_polar()
new_r = r ** (1 / k)
roots = []
for i in range(k):
roots.append((new_r, theta / k + (2 * pi * i) / k))
return roots
def e(z):
"""
complex exponential function
:param z:
:return:
"""
# e^(a + bi) = e^a * e^(bi)
if isinstance(z, (int, float)):
z = Complex(z)
new_re = exp(z.re) * cos(z.im)
new_im = exp(z.re) * sin(z.im)
return Complex(new_re, new_im)