Search code examples
rlogarithmalgebra

Does R have a function for the logarithm that deals with negative numeric values?


In mathematics, the exponential and logarithm functions can be generalised from the real numbers to the complex numbers. The exponential function is generalised using Euler's formula and the logarithm is generalised to the complex logarithm. The latter allows inputs that are complex numbers or negative real numbers.

Thankfully, the exponential and logarithmic function in R accommodate complex inputs. Both functions can take complex inputs and produce the appropriate exponential or logarithm of that input. However, if you put in a negative number as a numeric value (as opposed to a complex value), the log function does not produce the proper (complex) output for this input. Here is an example of what happens.

#Define negative real value as numeric/complex object
minusfour.numeric <- -4
minusfour.complex <- complex(real = -4, imaginary = 0)

#Apply the log function to these inputs
log(minusfour.complex)
[1] 1.386294+3.141593i

log(minusfour.numeric)
[1] NaN
Warning message:
In log(minusfour.numeric) : NaNs produced

Ideally, it would be nice if the log function gave the proper (complex) output when you give a negative numeric value as the input. unfortunately it does not appear to be programmed to do this.


My Question: Is there another logarithm function programmed in R that accommodates negative numeric inputs (i.e., gives the appropriate complex output for these inputs)?


Solution

  • Based on the upvoted comment from Hugh it looks like the simplest method is just to write the function as a variation of the underlying base log function. I've decided to go with a version that converts back to a real number at the end of the computation if none of the outputs have imaginary parts. Here is the code:

    Log <- function(x, base = exp(1)) {
      LOG <- base::log(as.complex(x), base = base)
      if (all(Im(LOG) == 0)) { LOG <- Re(LOG) }
      LOG }
    

    This code works for positive or negative numeric values and gives a numeric output when you give it a non-negative numeric input.

    #Apply the Log function to +4 and -4
    Log(-4)
    [1] 1.386294+3.141593i
    
    Log(4)
    [1] 1.386294