4
# [Now that Python has a complex data type built-in, this is not very
5
# useful, but it's still a nice example class]
7
# This module represents complex numbers as instances of the class Complex.
8
# A Complex instance z has two data attribues, z.re (the real part) and z.im
9
# (the imaginary part). In fact, z.re and z.im can have any value -- all
10
# arithmetic operators work regardless of the type of z.re and z.im (as long
11
# as they support numerical operations).
13
# The following functions exist (Complex is actually a class):
14
# Complex([re [,im]) -> creates a complex number from a real and an imaginary part
15
# IsComplex(z) -> true iff z is a complex number (== has .re and .im attributes)
16
# ToComplex(z) -> a complex number equal to z; z itself if IsComplex(z) is true
17
# if z is a tuple(re, im) it will also be converted
18
# PolarToComplex([r [,phi [,fullcircle]]]) ->
19
# the complex number z for which r == z.radius() and phi == z.angle(fullcircle)
20
# (r and phi default to 0)
21
# exp(z) -> returns the complex exponential of z. Equivalent to pow(math.e,z).
23
# Complex numbers have the following methods:
24
# z.abs() -> absolute value of z
25
# z.radius() == z.abs()
26
# z.angle([fullcircle]) -> angle from positive X axis; fullcircle gives units
27
# z.phi([fullcircle]) == z.angle(fullcircle)
29
# These standard functions and unary operators accept complex arguments:
36
# hash(z) -> a combination of hash(z.re) and hash(z.im) such that if z.im is zero
37
# the result equals hash(z.re)
38
# Note that hex(z) and oct(z) are not defined.
40
# These conversions accept complex arguments only if their imaginary part is zero:
44
# The following operators accept two complex numbers, or one complex number
45
# and one real number (int, long or float):
52
# Note that z1 % z2 and divmod(z1, z2) are not defined,
53
# nor are shift and mask operations.
55
# The standard module math does not support complex numbers.
56
# The cmath modules should be used instead.
59
# add a class Polar(r, phi) and mixed-mode arithmetic which
60
# chooses the most appropriate type for the result:
71
return hasattr(obj, 're') and hasattr(obj, 'im')
76
elif isinstance(obj, tuple):
81
def PolarToComplex(r = 0, phi = 0, fullcircle = twopi):
82
phi = phi * (twopi / fullcircle)
83
return Complex(math.cos(phi)*r, math.sin(phi)*r)
97
def __init__(self, re=0, im=0):
110
# this class is immutable, so setting self.re directly is
112
self.__dict__['re'] = _re
113
self.__dict__['im'] = _im
115
def __setattr__(self, name, value):
116
raise TypeError('Complex numbers are immutable')
121
return hash((self.re, self.im))
125
return 'Complex(%r)' % (self.re,)
127
return 'Complex(%r, %r)' % (self.re, self.im)
133
return 'Complex(%r, %r)' % (self.re, self.im)
136
return Complex(-self.re, -self.im)
142
return math.hypot(self.re, self.im)
146
raise ValueError("can't convert Complex with nonzero im to int")
151
raise ValueError("can't convert Complex with nonzero im to float")
152
return float(self.re)
154
def __cmp__(self, other):
155
other = ToComplex(other)
156
return cmp((self.re, self.im), (other.re, other.im))
158
def __rcmp__(self, other):
159
other = ToComplex(other)
160
return cmp(other, self)
163
return not (self.re == self.im == 0)
165
abs = radius = __abs__
167
def angle(self, fullcircle = twopi):
168
return (fullcircle/twopi) * ((halfpi - math.atan2(self.re, self.im)) % twopi)
172
def __add__(self, other):
173
other = ToComplex(other)
174
return Complex(self.re + other.re, self.im + other.im)
178
def __sub__(self, other):
179
other = ToComplex(other)
180
return Complex(self.re - other.re, self.im - other.im)
182
def __rsub__(self, other):
183
other = ToComplex(other)
186
def __mul__(self, other):
187
other = ToComplex(other)
188
return Complex(self.re*other.re - self.im*other.im,
189
self.re*other.im + self.im*other.re)
193
def __div__(self, other):
194
other = ToComplex(other)
195
d = float(other.re*other.re + other.im*other.im)
196
if not d: raise ZeroDivisionError('Complex division')
197
return Complex((self.re*other.re + self.im*other.im) / d,
198
(self.im*other.re - self.re*other.im) / d)
200
def __rdiv__(self, other):
201
other = ToComplex(other)
204
def __pow__(self, n, z=None):
206
raise TypeError('Complex does not support ternary pow()')
209
if self.im: raise TypeError('Complex to the Complex power')
210
else: return exp(math.log(self.re)*n)
212
r = pow(self.abs(), n)
214
return Complex(math.cos(phi)*r, math.sin(phi)*r)
216
def __rpow__(self, base):
217
base = ToComplex(base)
218
return pow(base, self)
222
return Complex(math.cos(z.im)*r,math.sin(z.im)*r)
225
def checkop(expr, a, b, value, fuzz = 1e-6):
226
print(' ', a, 'and', b, end=' ')
230
result = sys.exc_info()[0]
232
if isinstance(result, str) or isinstance(value, str):
233
ok = (result == value)
235
ok = abs(result - value) <= fuzz
237
print('!!\t!!\t!! should be', value, 'diff', abs(result - value))
240
print('test constructors')
242
# "expect" is an array [re,im] "got" the Complex.
243
( (0,0), Complex() ),
244
( (0,0), Complex() ),
245
( (1,0), Complex(1) ),
246
( (0,1), Complex(0,1) ),
247
( (1,2), Complex(Complex(1,2)) ),
248
( (1,3), Complex(Complex(1,2),1) ),
249
( (0,0), Complex(0,Complex(0,0)) ),
250
( (3,4), Complex(3,Complex(4)) ),
251
( (-1,3), Complex(1,Complex(3,2)) ),
252
( (-7,6), Complex(Complex(1,2),Complex(4,8)) ) )
254
for t in constructor_test:
256
if ((t[0][0]!=t[1].re)or(t[0][1]!=t[1].im)):
257
print(" expected", t[0], "got", t[1])
259
print(" ", cnt[1], "of", cnt[0], "tests failed")
264
(1, Complex(0,10), Complex(1,10)),
265
(Complex(0,10), 1, Complex(1,10)),
266
(Complex(0,10), Complex(1), Complex(1,10)),
267
(Complex(1), Complex(0,10), Complex(1,10)),
271
(1, Complex(0,10), Complex(1,-10)),
272
(Complex(0,10), 1, Complex(-1,10)),
273
(Complex(0,10), Complex(1), Complex(-1,10)),
274
(Complex(1), Complex(0,10), Complex(1,-10)),
278
(1, Complex(0,10), Complex(0, 10)),
279
(Complex(0,10), 1, Complex(0,10)),
280
(Complex(0,10), Complex(1), Complex(0,10)),
281
(Complex(1), Complex(0,10), Complex(0,10)),
285
(1, Complex(0,10), Complex(0, -0.1)),
286
(Complex(0, 10), 1, Complex(0, 10)),
287
(Complex(0, 10), Complex(1), Complex(0, 10)),
288
(Complex(1), Complex(0,10), Complex(0, -0.1)),
292
(1, Complex(0,10), 1),
293
(Complex(0,10), 1, Complex(0,10)),
294
(Complex(0,10), Complex(1), Complex(0,10)),
295
(Complex(1), Complex(0,10), 1),
296
(2, Complex(4,0), 16),
300
(1, Complex(0,10), 1),
301
(Complex(0,10), 1, -1),
302
(Complex(0,10), Complex(1), -1),
303
(Complex(1), Complex(0,10), 1),
306
for expr in sorted(testsuite):
309
for item in testsuite[expr]:
313
if __name__ == '__main__':