summaryrefslogtreecommitdiffstats
path: root/Demo/classes
diff options
context:
space:
mode:
Diffstat (limited to 'Demo/classes')
-rwxr-xr-xDemo/classes/Complex.py45
1 files changed, 36 insertions, 9 deletions
diff --git a/Demo/classes/Complex.py b/Demo/classes/Complex.py
index a9f5c2e..03c93fd 100755
--- a/Demo/classes/Complex.py
+++ b/Demo/classes/Complex.py
@@ -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 @@ def Im(obj):
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 exp(z):
def checkop(expr, a, b, value, fuzz = 1e-6):
- import sys
print ' ', a, 'and', b,
try:
result = eval(expr)
@@ -238,8 +245,28 @@ def checkop(expr, a, b, value, fuzz = 1e-6):
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),