简体   繁体   中英

Strange behavior of R

So, I have the following code in R:

y
a <- -0.1    
test <- (1/((y+as.numeric(!y))*(a-1)))  
test  
test^a  
-0.9090909^a 

Giving me the output:

> y  
 [1] 0.00000000 0.06024096 0.00000000 0.01098901 0.00000000 0.00000000
 [7] 0.01829268 0.00000000 0.06976744 0.00000000 0.04380665 0.01351351
[13] 0.00000000 0.00000000 0.00000000 0.00000000 0.00310559 0.00000000
[19] 0.00000000 0.00000000 0.09957447 0.00000000 0.03738318 0.00000000
> a <- -0.1
> test <- (1/((y+as.numeric(!y))*(a-1)))
> test
 [1]   -0.9090909  -15.0909091   -0.9090909  -82.7272727   -0.9090909
 [6]   -0.9090909  -49.6969697   -0.9090909  -13.0303030   -0.9090909
[11]  -20.7523511  -67.2727273   -0.9090909   -0.9090909   -0.9090909
[16]   -0.9090909 -292.7272727   -0.9090909   -0.9090909   -0.9090909
[21]   -9.1297591   -0.9090909  -24.3181818   -0.9090909  

> test^a  
 [1] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
[17] NaN NaN NaN NaN NaN NaN NaN NaN  

> -0.9090909^a  
[1] -1.009577

I do not understand why It gives me NaN when taking test to the power a, when clearly, I can simply copy a single value from test and raise it to the power a, and that works. Using test[1]^a does not work either.

-0.9090909 ^ a is the same as -(0.9090909 ^ a) . Notice the parentheses.

However, your test contains negative values, and you cannot take the root of a negative number. Try (-0.9090909) ^ a to verify this:

> (-0.9090909) ^ -0.1
[1] NaN

You are trying to take a root of a negative number. If you wish to do complex arithmetic you need to convert to complex

as.complex(test) ^ a
# [1] 0.9601644-0.3119763i 0.7249946-0.2355650i 0.9601644-0.3119763i
# [4] 0.6115633-0.1987090i 0.9601644-0.3119763i 0.9601644-0.3119763i
# [7] 0.6435367-0.2090978i 0.9601644-0.3119763i 0.7357171-0.2390490i
#[10] 0.9601644-0.3119763i 0.7022627-0.2281790i 0.6243418-0.2028609i
#[13] 0.9601644-0.3119763i 0.9601644-0.3119763i 0.9601644-0.3119763i
#[16] 0.9601644-0.3119763i 0.5389643-0.1751201i 0.9601644-0.3119763i
#[19] 0.9601644-0.3119763i 0.9601644-0.3119763i 0.7623605-0.2477059i
#[22] 0.9601644-0.3119763i 0.6912151-0.2245894i 0.9601644-0.3119763i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM