finding cube root in C++?

后端 未结 12 681
自闭症患者
自闭症患者 2020-12-03 15:18

Strange things happen when i try to find the cube root of a number.

The following code returns me undefined. In cmd : -1.#IND

cout<

        
12条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 15:39

    Here's a little function I knocked up.

    #define uniform() (rand()/(1.0 + RAND_MAX))
    
    double CBRT(double Z)
    {
        double guess = Z;
        double x, dx;
        int loopbreaker;
    
    retry:
        x = guess * guess * guess;
        loopbreaker = 0;
        while (fabs(x - Z) > FLT_EPSILON)
        {
            dx = 3 * guess*guess;
            loopbreaker++;
            if (fabs(dx) < DBL_EPSILON || loopbreaker > 53)
            {
                guess += uniform() * 2 - 1.0;
                goto retry;
            }
            guess -= (x - Z) / dx;
            x = guess*guess*guess;
        }
    
        return guess;
    }
    

    It uses Newton-Raphson to find a cube root.

    Sometime Newton -Raphson gets stuck, if the root is very close to 0 then the derivative can get large and it can oscillate. So I've clamped and forced it to restart if that happens. If you need more accuracy you can change the FLT_EPSILONs.

提交回复
热议问题