~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Demo/classes/Complex.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
ImportĀ upstreamĀ versionĀ 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Complex numbers
 
2
# ---------------
 
3
 
 
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
 
 
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]]]) ->
 
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).
 
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
# float(z)
 
43
#
 
44
# The following operators accept two complex numbers, or one complex number
 
45
# and one real number (int, long or float):
 
46
# z1 + z2
 
47
# z1 - z2
 
48
# z1 * z2
 
49
# z1 / z2
 
50
# pow(z1, z2)
 
51
# cmp(z1, z2)
 
52
# Note that z1 % z2 and divmod(z1, z2) are not defined,
 
53
# nor are shift and mask operations.
 
54
#
 
55
# The standard module math does not support complex numbers.
 
56
# The cmath modules should be used instead.
 
57
#
 
58
# Idea:
 
59
# add a class Polar(r, phi) and mixed-mode arithmetic which
 
60
# chooses the most appropriate type for the result:
 
61
# Complex for +,-,cmp
 
62
# Polar   for *,/,pow
 
63
 
 
64
import math
 
65
import sys
 
66
 
 
67
twopi = math.pi*2.0
 
68
halfpi = math.pi/2.0
 
69
 
 
70
def IsComplex(obj):
 
71
    return hasattr(obj, 're') and hasattr(obj, 'im')
 
72
 
 
73
def ToComplex(obj):
 
74
    if IsComplex(obj):
 
75
        return obj
 
76
    elif isinstance(obj, tuple):
 
77
        return Complex(*obj)
 
78
    else:
 
79
        return Complex(obj)
 
80
 
 
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)
 
84
 
 
85
def Re(obj):
 
86
    if IsComplex(obj):
 
87
        return obj.re
 
88
    return obj
 
89
 
 
90
def Im(obj):
 
91
    if IsComplex(obj):
 
92
        return obj.im
 
93
    return 0
 
94
 
 
95
class Complex:
 
96
 
 
97
    def __init__(self, re=0, im=0):
 
98
        _re = 0
 
99
        _im = 0
 
100
        if IsComplex(re):
 
101
            _re = re.re
 
102
            _im = re.im
 
103
        else:
 
104
            _re = re
 
105
        if IsComplex(im):
 
106
            _re = _re - im.im
 
107
            _im = _im + im.re
 
108
        else:
 
109
            _im = _im + im
 
110
        # this class is immutable, so setting self.re directly is
 
111
        # not possible.
 
112
        self.__dict__['re'] = _re
 
113
        self.__dict__['im'] = _im
 
114
 
 
115
    def __setattr__(self, name, value):
 
116
        raise TypeError('Complex numbers are immutable')
 
117
 
 
118
    def __hash__(self):
 
119
        if not self.im:
 
120
            return hash(self.re)
 
121
        return hash((self.re, self.im))
 
122
 
 
123
    def __repr__(self):
 
124
        if not self.im:
 
125
            return 'Complex(%r)' % (self.re,)
 
126
        else:
 
127
            return 'Complex(%r, %r)' % (self.re, self.im)
 
128
 
 
129
    def __str__(self):
 
130
        if not self.im:
 
131
            return repr(self.re)
 
132
        else:
 
133
            return 'Complex(%r, %r)' % (self.re, self.im)
 
134
 
 
135
    def __neg__(self):
 
136
        return Complex(-self.re, -self.im)
 
137
 
 
138
    def __pos__(self):
 
139
        return self
 
140
 
 
141
    def __abs__(self):
 
142
        return math.hypot(self.re, self.im)
 
143
 
 
144
    def __int__(self):
 
145
        if self.im:
 
146
            raise ValueError("can't convert Complex with nonzero im to int")
 
147
        return int(self.re)
 
148
 
 
149
    def __float__(self):
 
150
        if self.im:
 
151
            raise ValueError("can't convert Complex with nonzero im to float")
 
152
        return float(self.re)
 
153
 
 
154
    def __cmp__(self, other):
 
155
        other = ToComplex(other)
 
156
        return cmp((self.re, self.im), (other.re, other.im))
 
157
 
 
158
    def __rcmp__(self, other):
 
159
        other = ToComplex(other)
 
160
        return cmp(other, self)
 
161
 
 
162
    def __bool__(self):
 
163
        return not (self.re == self.im == 0)
 
164
 
 
165
    abs = radius = __abs__
 
166
 
 
167
    def angle(self, fullcircle = twopi):
 
168
        return (fullcircle/twopi) * ((halfpi - math.atan2(self.re, self.im)) % twopi)
 
169
 
 
170
    phi = angle
 
171
 
 
172
    def __add__(self, other):
 
173
        other = ToComplex(other)
 
174
        return Complex(self.re + other.re, self.im + other.im)
 
175
 
 
176
    __radd__ = __add__
 
177
 
 
178
    def __sub__(self, other):
 
179
        other = ToComplex(other)
 
180
        return Complex(self.re - other.re, self.im - other.im)
 
181
 
 
182
    def __rsub__(self, other):
 
183
        other = ToComplex(other)
 
184
        return other - self
 
185
 
 
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)
 
190
 
 
191
    __rmul__ = __mul__
 
192
 
 
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)
 
199
 
 
200
    def __rdiv__(self, other):
 
201
        other = ToComplex(other)
 
202
        return other / self
 
203
 
 
204
    def __pow__(self, n, z=None):
 
205
        if z is not None:
 
206
            raise TypeError('Complex does not support ternary pow()')
 
207
        if IsComplex(n):
 
208
            if n.im:
 
209
                if self.im: raise TypeError('Complex to the Complex power')
 
210
                else: return exp(math.log(self.re)*n)
 
211
            n = n.re
 
212
        r = pow(self.abs(), n)
 
213
        phi = n*self.angle()
 
214
        return Complex(math.cos(phi)*r, math.sin(phi)*r)
 
215
 
 
216
    def __rpow__(self, base):
 
217
        base = ToComplex(base)
 
218
        return pow(base, self)
 
219
 
 
220
def exp(z):
 
221
    r = math.exp(z.re)
 
222
    return Complex(math.cos(z.im)*r,math.sin(z.im)*r)
 
223
 
 
224
 
 
225
def checkop(expr, a, b, value, fuzz = 1e-6):
 
226
    print('       ', a, 'and', b, end=' ')
 
227
    try:
 
228
        result = eval(expr)
 
229
    except:
 
230
        result = sys.exc_info()[0]
 
231
    print('->', result)
 
232
    if isinstance(result, str) or isinstance(value, str):
 
233
        ok = (result == value)
 
234
    else:
 
235
        ok = abs(result - value) <= fuzz
 
236
    if not ok:
 
237
        print('!!\t!!\t!! should be', value, 'diff', abs(result - value))
 
238
 
 
239
def test():
 
240
    print('test constructors')
 
241
    constructor_test = (
 
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)) ) )
 
253
    cnt = [0,0]
 
254
    for t in constructor_test:
 
255
        cnt[0] += 1
 
256
        if ((t[0][0]!=t[1].re)or(t[0][1]!=t[1].im)):
 
257
            print("        expected", t[0], "got", t[1])
 
258
            cnt[1] += 1
 
259
    print("  ", cnt[1], "of", cnt[0], "tests failed")
 
260
    # test operators
 
261
    testsuite = {
 
262
            'a+b': [
 
263
                    (1, 10, 11),
 
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)),
 
268
            ],
 
269
            'a-b': [
 
270
                    (1, 10, -9),
 
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)),
 
275
            ],
 
276
            'a*b': [
 
277
                    (1, 10, 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)),
 
282
            ],
 
283
            'a/b': [
 
284
                    (1., 10, 0.1),
 
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)),
 
289
            ],
 
290
            'pow(a,b)': [
 
291
                    (1, 10, 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),
 
297
            ],
 
298
            'cmp(a,b)': [
 
299
                    (1, 10, -1),
 
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),
 
304
            ],
 
305
    }
 
306
    for expr in sorted(testsuite):
 
307
        print(expr + ':')
 
308
        t = (expr,)
 
309
        for item in testsuite[expr]:
 
310
            checkop(*(t+item))
 
311
 
 
312
 
 
313
if __name__ == '__main__':
 
314
    test()