[Python-checkins] python/dist/src/Demo/classes Complex.py,1.7,1.8

loewis at users.sourceforge.net loewis at users.sourceforge.net
Sat Apr 9 12:51:32 CEST 2005


Update of /cvsroot/python/python/dist/src/Demo/classes
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv6809

Modified Files:
	Complex.py 
Log Message:
Patch #1177597: Correct various bugs, add comments.


Index: Complex.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Demo/classes/Complex.py,v
retrieving revision 1.7
retrieving revision 1.8
diff -u -d -r1.7 -r1.8
--- Complex.py	12 Feb 2004 17:35:01 -0000	1.7
+++ Complex.py	9 Apr 2005 10:51:19 -0000	1.8
@@ -62,8 +62,8 @@
 # Complex for +,-,cmp
 # Polar   for *,/,pow
 
-
 import types, math
+import sys
 
 twopi = math.pi*2.0
 halfpi = math.pi/2.0
@@ -98,14 +98,22 @@
 class Complex:
 
     def __init__(self, re=0, im=0):
+        _re = 0
+        _im = 0
         if IsComplex(re):
-            im = i + Complex(0, re.im)
-            re = re.re
+            _re = re.re
+            _im = re.im
+        else:
+            _re = re
         if IsComplex(im):
-            re = re - im.im
-            im = im.re
-        self.__dict__['re'] = re
-        self.__dict__['im'] = im
+            _re = _re - im.im
+            _im = _im + im.re
+        else:
+            _im = _im + im
+        # this class is immutable, so setting self.re directly is
+        # not possible.
+        self.__dict__['re'] = _re
+        self.__dict__['im'] = _im
 
     def __setattr__(self, name, value):
         raise TypeError, 'Complex numbers are immutable'
@@ -224,7 +232,6 @@
 
 
 def checkop(expr, a, b, value, fuzz = 1e-6):
-    import sys
     print '       ', a, 'and', b,
     try:
         result = eval(expr)
@@ -238,8 +245,28 @@
     if not ok:
         print '!!\t!!\t!! should be', value, 'diff', abs(result - value)
 
-
 def test():
+    print 'test constructors'
+    constructor_test = (
+        # "expect" is an array [re,im] "got" the Complex.
+            ( (0,0), Complex() ),
+            ( (0,0), Complex() ),
+            ( (1,0), Complex(1) ),
+            ( (0,1), Complex(0,1) ),
+            ( (1,2), Complex(Complex(1,2)) ),
+            ( (1,3), Complex(Complex(1,2),1) ),
+            ( (0,0), Complex(0,Complex(0,0)) ),
+            ( (3,4), Complex(3,Complex(4)) ),
+            ( (-1,3), Complex(1,Complex(3,2)) ),
+            ( (-7,6), Complex(Complex(1,2),Complex(4,8)) ) )
+    cnt = [0,0]
+    for t in constructor_test:
+        cnt[0] += 1
+        if ((t[0][0]!=t[1].re)or(t[0][1]!=t[1].im)):
+            print "        expected", t[0], "got", t[1]
+            cnt[1] += 1
+    print "  ", cnt[1], "of", cnt[0], "tests failed"
+    # test operators
     testsuite = {
             'a+b': [
                     (1, 10, 11),



More information about the Python-checkins mailing list