deriving from complex

Schüle Daniel uval at rz.uni-karlsruhe.de
Tue Mar 7 19:07:09 EST 2006


what do you think of this design?

 >>> def polar(x,y=None):
...     if type(x) in (list,tuple) and len(x) == 2 and y is None:
...             return complex(x[0]*cos(x[1]), x[0]*sin(x[1]))
...     if type(x) is complex and y is None:
...             return (abs(x), atan2(x.imag,x.real))
...     if type(x) in (float, int, long) and type(y) in (float, int, long):
...             return complex(x*cos(y), x*sin(y))
...
 >>> polar(2**0.5, 45.0/360*2*pi)
(1.0000000000000002+1j)
 >>> polar((2**0.5, 45.0/360*2*pi))
(1.0000000000000002+1j)
 >>> polar([2**0.5, 45.0/360*2*pi])
(1.0000000000000002+1j)
 >>> polar(1+1j)
(1.4142135623730951, 0.78539816339744828)
 >>>

btw I like how Ruby handles the creation of complex numbers

c = Complex(1,1)
p = Complex.polar(1,45.0/360*2*PI)

Regards, Daniel




More information about the Python-list mailing list