Tim Peters at
Sun Sep 21 22:33:03 CEST 2003

[David Eppstein]
> Why doesn't this work?
> >>> import math
> >>> math.exp(1j*math.pi)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: can't convert complex to float; use e.g. abs(z)
> The expected answer, of course, is -1.

The math module mostly provides thin wrappers around the standard C
library's functions of the same names.  They don't accept complex arguments.
Use cmath instead:

>>> import cmath
>>> cmath.exp(1j*cmath.pi)

> It does work if you do it like this:
> >>> math.e**(1j*math.pi) (-1+1.2246467991473532e-16j)

Or, in this case, use the builtin pow(), which looks for a __pow__ method,
which is the same thing "**" does.  Math libraries in general can return a
better result for exp(x) than e**x, though, since the latter form uses a
machine approximation to e as the base.

> So why not math.exp(complex)?

The basic thought is that most Python users don't know or care about complex
numbers, so it's better to give them an exception than have, e.g., sqrt(-1)
or asin(10) return a surprising result.  The relatively rare users who are
comfortable working with complex numbers can use them by importing the cmath

More information about the Python-list mailing list