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
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)
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 Java something like this :
There are 3 cube-roots. Assuming you want the root that is real, you should do this:
x = 8; // Your value
if (x > 0)
System.out.println(Math.pow(x, 1.0 / 3.0));
else
System.out.println(-Math.pow(-x, 1.0 / 3.0));