Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4a1e48c

Browse files
committed
Patch #1177597: Correct various bugs, add comments.
1 parent 629496b commit 4a1e48c

1 file changed

Lines changed: 36 additions & 9 deletions

File tree

Demo/classes/Complex.py

Lines changed: 36 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,8 @@
6262
# Complex for +,-,cmp
6363
# Polar for *,/,pow
6464

65-
6665
import types, math
66+
import sys
6767

6868
twopi = math.pi*2.0
6969
halfpi = math.pi/2.0
@@ -98,14 +98,22 @@ def Im(obj):
9898
class Complex:
9999

100100
def __init__(self, re=0, im=0):
101+
_re = 0
102+
_im = 0
101103
if IsComplex(re):
102-
im = i + Complex(0, re.im)
103-
re = re.re
104+
_re = re.re
105+
_im = re.im
106+
else:
107+
_re = re
104108
if IsComplex(im):
105-
re = re - im.im
106-
im = im.re
107-
self.__dict__['re'] = re
108-
self.__dict__['im'] = im
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
109117

110118
def __setattr__(self, name, value):
111119
raise TypeError, 'Complex numbers are immutable'
@@ -224,7 +232,6 @@ def exp(z):
224232

225233

226234
def checkop(expr, a, b, value, fuzz = 1e-6):
227-
import sys
228235
print ' ', a, 'and', b,
229236
try:
230237
result = eval(expr)
@@ -238,8 +245,28 @@ def checkop(expr, a, b, value, fuzz = 1e-6):
238245
if not ok:
239246
print '!!\t!!\t!! should be', value, 'diff', abs(result - value)
240247

241-
242248
def test():
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
243270
testsuite = {
244271
'a+b': [
245272
(1, 10, 11),

0 commit comments

Comments
 (0)