Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex numbers in R vs. Matlab

I observed the following phenomenon when using R and Matlab.

When I apply log to a negative number in R, I get the following error message:

Warning message: In log(-1) : NaNs produced

However, when I apply log to a negative number in Matlab, I get e.g., the following complex numbers:

log(-1): 0.0000 + 3.1416i

log(-5): 1.6094 + 3.1416i

Is there any way to achieve the same behavior in R? Or is there anything in favor of the default option in R?

like image 622
salomon Avatar asked Apr 23 '21 16:04

salomon


Video Answer


1 Answers

log gives you complex when you give it complex in the first place.

log(-1+0i)
# [1] 0+3.141593i
log(-5+0i)
# [1] 1.609438+3.141593i

I don't know why it doesn't give an option to do this by default, but then again I don't work in complex numbers all the time.

If you want to do this programmatically, you can use as.complex:

log(as.complex(-1))
# [1] 0+3.141593i

or even make a helper function simplify it for you:

mylog <- function(x, ...) log(as.complex(x), ...)
mylog(-1)
# [1] 0+3.141593i
like image 96
r2evans Avatar answered Oct 16 '22 23:10

r2evans