R是否有处理负数值的对数函数?

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

在数学中,指数函数和对数函数可以从实数推广到复数。指数函数用欧拉公式推广,对数推广到complex logarithm。后者允许输入复数或负实数。

幸运的是,R 中的 exponential and logarithmic function 可以容纳复杂的输入。这两个函数都可以采用复数输入并生成该输入的适当指数或对数。但是,如果您输入负数作为数值(而不是复数),log 函数不会为此输入生成正确的(复数)输出。这是发生的情况的示例。

#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

理想情况下,如果 log 函数在您给出负数值作为输入时给出正确的(复数)输出,那就太好了。不幸的是,它似乎没有被编程为执行此操作。


我的问题:是否在 R 中编写了另一个对数函数来适应负数输入(即,为这些输入提供适当的复数输出)?

根据 Hugh 的赞成评论,看起来最简单的方法就是将函数编写为底层基础 log 函数的变体。如果 none 的输出有虚部,我决定使用一个在计算结束时转换回实数的版本。这是代码:

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

此代码适用于正数值或负数值,并在您为其提供 non-negative 数字输入时给出数字输出。

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

Log(4)
[1] 1.386294