Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real cube root of a negative number

Tags:

r

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!

like image 628
Zhang18 Avatar asked Nov 05 '12 16:11

Zhang18


2 Answers

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
like image 129
Josh O'Brien Avatar answered Sep 29 '22 01:09

Josh O'Brien


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)
like image 42
IRTFM Avatar answered Sep 28 '22 23:09

IRTFM