问题
math.exp()
doesn't work for complex numbers:
>>> math.exp (math.pi*1j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
This doesn't hurt me much, as **
works as intended:
>>> math.e ** (math.pi*1j)
(-1+1.2246467991473532e-16j)
Now the problem is with logarithms. math.log
doesn't work for negative numbers:
>>> math.log(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
(Expected result: (0+3.141592653589793j)
)
How can I calculate a logarithm in python whose result is complex? (Preferably without implementing it myself)
回答1:
The math documentation explicitly says that it does not support complex numbers. If you want a library in python that does, you should use cmath instead.
Cmath stands for Complex Math.
cmath has most of the same interface as math, so for your example you could just do the following:
import cmath
cmath.log(-1)
来源:https://stackoverflow.com/questions/18284623/python3-calculating-complex-exponents-and-logarithms