faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 3 people (33%) answered Yes
Recently 0 of 1 people (0%) answered Yes

Entry

Trouble with complexes

Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 72, Travis Oliphant


"""
Packages: maths
"""
"""
> Does anyone know of any reason raising a complex number to a power
> doesn't work? (3+2j)^5, for example, gives me
> 
> TypeError: bad operand type(s) for ^
> 
> Is there any way to fix this?
Use the ** operator:
"""
print (3+2j)**2
# (5+12j)
"""
> Also, I was wondering if there's a nice way to implement r*exp(1j*theta)
> representations of complexes. I was originally thinking of making a new
> 'Polar' class, but then I would get errors if I applied the cmath
> functions to instances of this class. Any ideas? Thanks.
Here is a sample class that lets you do standard operations.  To apply
cmath functions use
p = Polar(radius, angle)
cmath.XXX(p.cval)
"""
class Polar:
    def __init__(self,r,theta):
        self.r = r
        self.th = theta
        self.cval = r*exp(1j*theta)
    def __coerce__(self,other):
        return (self.cval, other)
    def __getattr__(self,name):
        if name not in ['r','th','cval']:
            print "Attribute not found."        
        return 0
    def __setattr__(self,name,value):
        if name=='r':
            self.__dict__[name] = value
        elif name=='th':
            self.__dict__[name] = value
        elif name=='cval':
            self.__dict__[name] = value
        else:
            print "Attribute not found."
        self.__dict__['cval'] = self.r*exp(1j*self.th)
    def __str__(self):
        return "(%f, %f)" % (self.r, self.th)
    def __repr__(self):
        return "Polar(%f, %f)" % (self.r, self.th)