Hyperboreus
Hyperboreus

Reputation: 32429

Python3: Calculating complex exponents and logarithms

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)

Upvotes: 2

Views: 2288

Answers (1)

Slater Victoroff
Slater Victoroff

Reputation: 21914

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)

Upvotes: 6

Related Questions