[R] cube root on array
Marc Schwartz
marc_schwartz at me.com
Sat Dec 12 16:50:27 CET 2009
On Dec 12, 2009, at 9:31 AM, Rodrigo Tsai wrote:
> Dear R developers,
>
> is that right?
>
>> -27^(1/3)
> [1] -3
library(fortunes)
> fortune("^")
Thomas Lumley: The precedence of ^ is higher than that of unary minus.
It may be surprising, [...]
Hervé Pagès: No, it's not surprising. At least to me... In the country
where I grew up, I've been teached that -x^2 means -(x^2) not (-x)^2.
-- Thomas Lumley and Hervé Pagès (both explaining that operator
precedence is working perfectly well)
R-devel (January 2006)
Also see R FAQ 7.33:
http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-are-powers-of-negative-numbers-wrong_003f
Using the example in the FAQ:
> as.list(quote(-27^(1/3)))
[[1]]
`-`
[[2]]
27^(1/3)
So what you see above is the consequence of operator precedence, thus:
> (-27)^(1/3)
[1] NaN
which is what you are getting below for the first value in the vector.
>> c(-27,27)^(1/3)
> [1] NaN 3
>
> i'm using sign( c(-27,27) ) * abs( c(-27,27)) ^(1/3) ,
> thanks
>
That seems to be a reasonable approach and if memory serves, has been
posted to the list previously.
HTH,
Marc Schwartz
More information about the R-help
mailing list