C - finding cube root of a negative number with pow function

后端 未结 4 523
没有蜡笔的小新
没有蜡笔的小新 2021-01-17 12:13

In real world cube root for a negative number should exist: cuberoot(-1)=-1, that means (-1)*(-1)*(-1)=-1 or cuberoot(-27)=-3, that me

4条回答
  •  半阙折子戏
    2021-01-17 12:47

    As Stephen Canon answered, to correct function to use in this case is cbrt(). If you don't know the exponent beforehand, you can look into the cpow() function.

    
    #include 
    #include 
    #include 
    
    int main(void)
    {
        printf("cube root cbrt: %g\n", cbrt(-27.));
        printf("cube root pow: %g\n", pow(-27., 1./3.));
        double complex a, b, c;
        a = -27.;
        b = 1. / 3;
        c = cpow(a, b);
        printf("cube root cpow: (%g, %g), abs: %g\n", creal(c), cimag(c), cabs(c));
        return 0;
    }
    
    

    prints

    cube root cbrt: -3
    cube root pow: -nan
    cube root cpow: (1.5, 2.59808), abs: 3
    

    Keep in mind the definition of the complex power: cpow(a, b) = cexp(b* clog(a)).

提交回复
热议问题