I'm trying to see if there is a function to directly get the real cube root of a negative number. For example, in Java, there is the Math.cbrt()
function. I'm looking for the equivalent in R.
Otherwise, my current hack is:
x <- -8
sign(x) * abs(x)^(1/3)
which is very inelegant and cumbersome to type every time. Thx!
Sounds like you just need to define your own Math.cbrt()
function.
That will turn performing the operation from something inelegant and cumbersome to something clean, expressive, and easy to apply:
Math.cbrt <- function(x) {
sign(x) * abs(x)^(1/3)
}
x <- c(-1, -8, -27, -64)
Math.cbrt(x)
# [1] -1 -2 -3 -4
In R you probably need to define a new function that limits the results to your goals:
> realpow <- function(x,rad) if(x < 0){ - (-x)^(rad)}else{x^rad}
> realpow(-8, 1/3)
[1] -2
> realpow(8, 1/3)
[1] 2
It's possible to make an infix operation if you quote the operator and use surrounding "%" signs in its name. Because its precedence is low, you will need to use parentheses, but you already appear to know that.
> `%r^%` <- function(x, rad) realpow(x,rad)
> -8 %r^% 1/3
[1] -2.666667 # Wrong
> -8 %r^% (1/3)
[1] -2 #Correct
Agree with incorporating the questioner's version for its vectorized capacity:
`%r^%` <- function(x, rad) sign(x)*abs(x)^(rad)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With