trouble with complex numbers

Christian Heimes lists at cheimes.de
Wed Aug 5 05:21:18 EDT 2009


Dr. Phillip M. Feldman wrote:
> When I try to compute the phase of a complex number, I get an error message:
> 
> In [3]: from cmath import *
> In [4]: x=1+1J
> In [5]: phase(x)
> <snip>
> NameError: name 'phase' is not defined
> <snip>
> AttributeError: 'complex' object has no attribute 'phase'
> 
> Any advice will be appreciated.

phase() has been added to Python 2.6 and 3.0. It's not available in 
Python 2.5 and earlier. If you'd used cmath.phase() instead of the ugly 
"from cmath import *" statement you'd have seen the correct error message.

You can write your own phase() function. This function is mostly correct 
unless either the real and/or the imag part is NaN or INF.

from math import atan2

def phase(z):
     z += 1j # convert int, long, float to complex
     return atan2(z.imag, z.real)




More information about the Python-list mailing list