Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 1 | # Complex numbers |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 2 | # --------------- |
| 3 | |
Guido van Rossum | 72ba616 | 1996-07-30 19:02:01 +0000 | [diff] [blame] | 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] |
| 6 | |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 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). |
| 12 | # |
| 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]]]) -> |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 19 | # the complex number z for which r == z.radius() and phi == z.angle(fullcircle) |
| 20 | # (r and phi default to 0) |
Guido van Rossum | 72ba616 | 1996-07-30 19:02:01 +0000 | [diff] [blame] | 21 | # exp(z) -> returns the complex exponential of z. Equivalent to pow(math.e,z). |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 22 | # |
| 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) |
| 28 | # |
| 29 | # These standard functions and unary operators accept complex arguments: |
| 30 | # abs(z) |
| 31 | # -z |
| 32 | # +z |
| 33 | # not z |
| 34 | # repr(z) == `z` |
| 35 | # str(z) |
| 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. |
| 39 | # |
| 40 | # These conversions accept complex arguments only if their imaginary part is zero: |
| 41 | # int(z) |
| 42 | # long(z) |
| 43 | # float(z) |
| 44 | # |
| 45 | # The following operators accept two complex numbers, or one complex number |
| 46 | # and one real number (int, long or float): |
| 47 | # z1 + z2 |
| 48 | # z1 - z2 |
| 49 | # z1 * z2 |
| 50 | # z1 / z2 |
| 51 | # pow(z1, z2) |
| 52 | # cmp(z1, z2) |
| 53 | # Note that z1 % z2 and divmod(z1, z2) are not defined, |
| 54 | # nor are shift and mask operations. |
| 55 | # |
| 56 | # The standard module math does not support complex numbers. |
| 57 | # (I suppose it would be easy to implement a cmath module.) |
| 58 | # |
| 59 | # Idea: |
| 60 | # add a class Polar(r, phi) and mixed-mode arithmetic which |
| 61 | # chooses the most appropriate type for the result: |
| 62 | # Complex for +,-,cmp |
| 63 | # Polar for *,/,pow |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 64 | |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 65 | import types, math |
Martin v. Löwis | 4a1e48c | 2005-04-09 10:51:19 +0000 | [diff] [blame] | 66 | import sys |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 67 | |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 68 | twopi = math.pi*2.0 |
| 69 | halfpi = math.pi/2.0 |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 70 | |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 71 | def IsComplex(obj): |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 72 | return hasattr(obj, 're') and hasattr(obj, 'im') |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 73 | |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 74 | def ToComplex(obj): |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 75 | if IsComplex(obj): |
| 76 | return obj |
| 77 | elif type(obj) == types.TupleType: |
| 78 | return apply(Complex, obj) |
| 79 | else: |
| 80 | return Complex(obj) |
Guido van Rossum | 7565b93 | 1993-12-17 14:23:52 +0000 | [diff] [blame] | 81 | |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 82 | def PolarToComplex(r = 0, phi = 0, fullcircle = twopi): |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 83 | phi = phi * (twopi / fullcircle) |
| 84 | return Complex(math.cos(phi)*r, math.sin(phi)*r) |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 85 | |
| 86 | def Re(obj): |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 87 | if IsComplex(obj): |
| 88 | return obj.re |
| 89 | else: |
| 90 | return obj |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 91 | |
| 92 | def Im(obj): |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 93 | if IsComplex(obj): |
| 94 | return obj.im |
| 95 | else: |
| 96 | return obj |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 97 | |
| 98 | class Complex: |
| 99 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 100 | def __init__(self, re=0, im=0): |
Martin v. Löwis | 4a1e48c | 2005-04-09 10:51:19 +0000 | [diff] [blame] | 101 | _re = 0 |
| 102 | _im = 0 |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 103 | if IsComplex(re): |
Martin v. Löwis | 4a1e48c | 2005-04-09 10:51:19 +0000 | [diff] [blame] | 104 | _re = re.re |
| 105 | _im = re.im |
| 106 | else: |
| 107 | _re = re |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 108 | if IsComplex(im): |
Martin v. Löwis | 4a1e48c | 2005-04-09 10:51:19 +0000 | [diff] [blame] | 109 | _re = _re - im.im |
| 110 | _im = _im + im.re |
| 111 | else: |
| 112 | _im = _im + im |
| 113 | # this class is immutable, so setting self.re directly is |
| 114 | # not possible. |
| 115 | self.__dict__['re'] = _re |
| 116 | self.__dict__['im'] = _im |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 117 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 118 | def __setattr__(self, name, value): |
| 119 | raise TypeError, 'Complex numbers are immutable' |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 120 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 121 | def __hash__(self): |
| 122 | if not self.im: return hash(self.re) |
| 123 | mod = sys.maxint + 1L |
| 124 | return int((hash(self.re) + 2L*hash(self.im) + mod) % (2L*mod) - mod) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 125 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 126 | def __repr__(self): |
| 127 | if not self.im: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 128 | return 'Complex(%r)' % (self.re,) |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 129 | else: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 130 | return 'Complex(%r, %r)' % (self.re, self.im) |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 131 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 132 | def __str__(self): |
| 133 | if not self.im: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 134 | return repr(self.re) |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 135 | else: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 136 | return 'Complex(%r, %r)' % (self.re, self.im) |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 137 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 138 | def __neg__(self): |
| 139 | return Complex(-self.re, -self.im) |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 140 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 141 | def __pos__(self): |
| 142 | return self |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 143 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 144 | def __abs__(self): |
| 145 | # XXX could be done differently to avoid overflow! |
| 146 | return math.sqrt(self.re*self.re + self.im*self.im) |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 147 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 148 | def __int__(self): |
| 149 | if self.im: |
| 150 | raise ValueError, "can't convert Complex with nonzero im to int" |
| 151 | return int(self.re) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 152 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 153 | def __long__(self): |
| 154 | if self.im: |
| 155 | raise ValueError, "can't convert Complex with nonzero im to long" |
| 156 | return long(self.re) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 157 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 158 | def __float__(self): |
| 159 | if self.im: |
| 160 | raise ValueError, "can't convert Complex with nonzero im to float" |
| 161 | return float(self.re) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 162 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 163 | def __cmp__(self, other): |
| 164 | other = ToComplex(other) |
| 165 | return cmp((self.re, self.im), (other.re, other.im)) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 166 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 167 | def __rcmp__(self, other): |
| 168 | other = ToComplex(other) |
| 169 | return cmp(other, self) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 170 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 171 | def __nonzero__(self): |
| 172 | return not (self.re == self.im == 0) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 173 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 174 | abs = radius = __abs__ |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 175 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 176 | def angle(self, fullcircle = twopi): |
| 177 | return (fullcircle/twopi) * ((halfpi - math.atan2(self.re, self.im)) % twopi) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 178 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 179 | phi = angle |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 180 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 181 | def __add__(self, other): |
| 182 | other = ToComplex(other) |
| 183 | return Complex(self.re + other.re, self.im + other.im) |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 184 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 185 | __radd__ = __add__ |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 186 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 187 | def __sub__(self, other): |
| 188 | other = ToComplex(other) |
| 189 | return Complex(self.re - other.re, self.im - other.im) |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 190 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 191 | def __rsub__(self, other): |
| 192 | other = ToComplex(other) |
| 193 | return other - self |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 194 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 195 | def __mul__(self, other): |
| 196 | other = ToComplex(other) |
| 197 | return Complex(self.re*other.re - self.im*other.im, |
| 198 | self.re*other.im + self.im*other.re) |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 199 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 200 | __rmul__ = __mul__ |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 201 | |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 202 | def __div__(self, other): |
| 203 | other = ToComplex(other) |
| 204 | d = float(other.re*other.re + other.im*other.im) |
| 205 | if not d: raise ZeroDivisionError, 'Complex division' |
| 206 | return Complex((self.re*other.re + self.im*other.im) / d, |
| 207 | (self.im*other.re - self.re*other.im) / d) |
| 208 | |
| 209 | def __rdiv__(self, other): |
| 210 | other = ToComplex(other) |
| 211 | return other / self |
| 212 | |
| 213 | def __pow__(self, n, z=None): |
| 214 | if z is not None: |
| 215 | raise TypeError, 'Complex does not support ternary pow()' |
| 216 | if IsComplex(n): |
| 217 | if n.im: |
| 218 | if self.im: raise TypeError, 'Complex to the Complex power' |
| 219 | else: return exp(math.log(self.re)*n) |
| 220 | n = n.re |
| 221 | r = pow(self.abs(), n) |
| 222 | phi = n*self.angle() |
| 223 | return Complex(math.cos(phi)*r, math.sin(phi)*r) |
| 224 | |
| 225 | def __rpow__(self, base): |
| 226 | base = ToComplex(base) |
| 227 | return pow(base, self) |
| 228 | |
Guido van Rossum | 72ba616 | 1996-07-30 19:02:01 +0000 | [diff] [blame] | 229 | def exp(z): |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 230 | r = math.exp(z.re) |
| 231 | return Complex(math.cos(z.im)*r,math.sin(z.im)*r) |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 232 | |
| 233 | |
| 234 | def checkop(expr, a, b, value, fuzz = 1e-6): |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 235 | print ' ', a, 'and', b, |
| 236 | try: |
| 237 | result = eval(expr) |
| 238 | except: |
| 239 | result = sys.exc_type |
| 240 | print '->', result |
| 241 | if (type(result) == type('') or type(value) == type('')): |
| 242 | ok = result == value |
| 243 | else: |
| 244 | ok = abs(result - value) <= fuzz |
| 245 | if not ok: |
| 246 | print '!!\t!!\t!! should be', value, 'diff', abs(result - value) |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 247 | |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 248 | def test(): |
Martin v. Löwis | 4a1e48c | 2005-04-09 10:51:19 +0000 | [diff] [blame] | 249 | print 'test constructors' |
| 250 | constructor_test = ( |
| 251 | # "expect" is an array [re,im] "got" the Complex. |
| 252 | ( (0,0), Complex() ), |
| 253 | ( (0,0), Complex() ), |
| 254 | ( (1,0), Complex(1) ), |
| 255 | ( (0,1), Complex(0,1) ), |
| 256 | ( (1,2), Complex(Complex(1,2)) ), |
| 257 | ( (1,3), Complex(Complex(1,2),1) ), |
| 258 | ( (0,0), Complex(0,Complex(0,0)) ), |
| 259 | ( (3,4), Complex(3,Complex(4)) ), |
| 260 | ( (-1,3), Complex(1,Complex(3,2)) ), |
| 261 | ( (-7,6), Complex(Complex(1,2),Complex(4,8)) ) ) |
| 262 | cnt = [0,0] |
| 263 | for t in constructor_test: |
| 264 | cnt[0] += 1 |
| 265 | if ((t[0][0]!=t[1].re)or(t[0][1]!=t[1].im)): |
| 266 | print " expected", t[0], "got", t[1] |
| 267 | cnt[1] += 1 |
| 268 | print " ", cnt[1], "of", cnt[0], "tests failed" |
| 269 | # test operators |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 270 | testsuite = { |
| 271 | 'a+b': [ |
| 272 | (1, 10, 11), |
| 273 | (1, Complex(0,10), Complex(1,10)), |
| 274 | (Complex(0,10), 1, Complex(1,10)), |
| 275 | (Complex(0,10), Complex(1), Complex(1,10)), |
| 276 | (Complex(1), Complex(0,10), Complex(1,10)), |
| 277 | ], |
| 278 | 'a-b': [ |
| 279 | (1, 10, -9), |
| 280 | (1, Complex(0,10), Complex(1,-10)), |
| 281 | (Complex(0,10), 1, Complex(-1,10)), |
| 282 | (Complex(0,10), Complex(1), Complex(-1,10)), |
| 283 | (Complex(1), Complex(0,10), Complex(1,-10)), |
| 284 | ], |
| 285 | 'a*b': [ |
| 286 | (1, 10, 10), |
| 287 | (1, Complex(0,10), Complex(0, 10)), |
| 288 | (Complex(0,10), 1, Complex(0,10)), |
| 289 | (Complex(0,10), Complex(1), Complex(0,10)), |
| 290 | (Complex(1), Complex(0,10), Complex(0,10)), |
| 291 | ], |
| 292 | 'a/b': [ |
| 293 | (1., 10, 0.1), |
| 294 | (1, Complex(0,10), Complex(0, -0.1)), |
| 295 | (Complex(0, 10), 1, Complex(0, 10)), |
| 296 | (Complex(0, 10), Complex(1), Complex(0, 10)), |
| 297 | (Complex(1), Complex(0,10), Complex(0, -0.1)), |
| 298 | ], |
| 299 | 'pow(a,b)': [ |
| 300 | (1, 10, 1), |
| 301 | (1, Complex(0,10), 1), |
| 302 | (Complex(0,10), 1, Complex(0,10)), |
| 303 | (Complex(0,10), Complex(1), Complex(0,10)), |
| 304 | (Complex(1), Complex(0,10), 1), |
| 305 | (2, Complex(4,0), 16), |
| 306 | ], |
| 307 | 'cmp(a,b)': [ |
| 308 | (1, 10, -1), |
| 309 | (1, Complex(0,10), 1), |
| 310 | (Complex(0,10), 1, -1), |
| 311 | (Complex(0,10), Complex(1), -1), |
| 312 | (Complex(1), Complex(0,10), 1), |
| 313 | ], |
| 314 | } |
| 315 | exprs = testsuite.keys() |
| 316 | exprs.sort() |
| 317 | for expr in exprs: |
| 318 | print expr + ':' |
| 319 | t = (expr,) |
| 320 | for item in testsuite[expr]: |
| 321 | apply(checkop, t+item) |
| 322 | |
Guido van Rossum | e876949 | 1992-08-13 12:14:11 +0000 | [diff] [blame] | 323 | |
Guido van Rossum | 81a12bc | 1994-10-08 18:56:41 +0000 | [diff] [blame] | 324 | if __name__ == '__main__': |
Andrew M. Kuchling | 946c53e | 2003-04-24 17:13:18 +0000 | [diff] [blame] | 325 | test() |