Monday, March 27, 2017

Logarithms of Negative Numbers

A plot of log(x) looks something like the following:

As x decreases to zero log(x) approaches negative infinity. For negative values of real x, the log function is undefined. For example, consider the following numpy interaction:

>>> import numpy as np
>>> np.log(1)
>>> np.log(-1)
__main__:1: RuntimeWarning: invalid value encountered in log

If I try to do the same in Octave, I get something different, and interesting.

octave:1> log(1)
ans = 0
octave:2> log(-1)
ans =  0.00000 + 3.14159i

The answer makes sense if we expand the scope of "x" from real to complex. We know Euler's famous identity, \(e^{i \pi} = -1\). Logarithms of negative numbers exist. They just exist in the complex plane, rather than on the real number line.

Octave's answer above just takes the logarithm of both sides of Euler's identity.

We can make python behave similarly by explicitly specifying the complex nature of the argument. So while log(-1) did not work above, the following works just as expected.

>>> np.log(-1+0j)

For x < 0, if we plot the absolute value of the complex number, then we get a nice symmetric plot for log(x).


  • In matlab, the command reallog is similar to np.log

No comments: