Computes the cube root of a floating-point number, without using library functions. One decimal place.

The idea of ​​this question is to judge whether the number is greater than 0 or less than 0. We know that f(x)=x^3 is monotonically increasing in R, so the smaller the function value, the smaller the variable. So classify the discussion

<script>

        function cubeRoot ( n ) { ;

            //Judge whether this number is a positive integer or a negative number. Since it is stipulated that a decimal must be reserved, it will be increased or decreased in the form of 0.1 each time it is incremented and decremented.

            if (n >= 0) {

                for (var i = 0; ; i += 0.1) {

                   //This is similar to the knowledge of the zero point of the high school function f(x1)<0 f(x2)>0, then there must be a zero point on (x1,x2) (the function is continuous)

                    if (i ** 3 <= n && (i + 0.1) ** 3 >= n) {

                        break;

                    }

                }

                //Because it is cubed, it is rounded according to the percentile, so if the cube of the value after adding 0.05 is smaller than n, it means that the cube of i+1 is closer to n, so return i+1 and keep one decimal places

                if ((i + 0.05) ** 3 <= n) {

                    return (i + 0.1).toFixed(1)

                }

                return i.toFixed(1)

            }

            if (n < 0) {

                for (var i = 0; ; i -= 0.1) {

                    //x^3 is monotonically increasing on (-infinity, 0), so the smaller it is, the smaller it is. It is greater than n at the beginning, and after the subtraction, the third power is less than n

                    if (i ** 3 >= n && (i - 0.1) ** 3 <= n) {

                        break;

                    }

                }

                //Similarly, if the third power is less than n after adding 0.05, it means that i+1 is closer to the cube root of n

                if ((i + 0.05) ** 3 <= n) {

                    return (i + 0.1).toFixed(1)

                }

                return i.toFixed(1)

            }

        }

    </script>

Guess you like

Origin blog.csdn.net/weixin_68067009/article/details/124458134