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

后端 未结 4 401
没有蜡笔的小新
没有蜡笔的小新 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:30

    there is. Remember: x^(1/3) = -(-x)^(1/3). So the following should do it:

    double cubeRoot(double d) {
      if (d < 0.0) {
        return -cubeRoot(-d);
      }
      else {
        return pow(d,1.0/3.0);
      }
    }
    

    Written without compiling, so there may be syntax errors.

    Greetings, Jost

    0 讨论(0)
  • 2021-01-17 12:41

    7.12.7.1 The cbrt functions

    Synopsis

    #include <math.h>
    double cbrt(double x);
    float cbrtf(float x);
    long double cbrtl(long double x);
    

    Description

    The cbrt functions compute the real cube root of x.


    If you're curious, pow can't be used to compute cube roots because one-third is not expressible as a floating-point number. You're actually asking pow to raise -27.0 to a rational power very nearly equal to 1/3; there is no real result that would be appropriate.

    0 讨论(0)
  • 2021-01-17 12:44

    Using Newton's Method:

    def cubicroot(num):
      flag = 1
      if num < 0:
        flag = -1
        num = num - num - num
      x0 = num / 2.
      x1 = x0 - (((x0 * x0 * x0) - num) / (3. * x0 * x0))
      while(round(x0) != round(x1)):
        x0 = x1
        x1 = x0 - (((x0 * x0 * x0) - num) / (3. * x0 * x0))
      return x1 * flag
    
    print cubicroot(27)
    
    0 讨论(0)
  • 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 <stdio.h>
    #include <math.h>
    #include <complex.h>
    
    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)).

    0 讨论(0)
提交回复
热议问题