Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
387 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...