Real cube root of a negative number

前端 未结 3 2014
长情又很酷
长情又很酷 2020-12-03 21:10

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

相关标签:
3条回答
  • 2020-12-03 21:25

    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)
    
    0 讨论(0)
  • 2020-12-03 21:45

    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
    
    0 讨论(0)
  • 2020-12-03 21:50

    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));
    
    0 讨论(0)
提交回复
热议问题