Python3: Calculating complex exponents and logarithms

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 01:37:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!