直接上代码,牛顿法的性能会高很多,推荐牛顿法,他的收敛速度非常快。

import static tech.yinode.demo.Print.*;


class Index {

    public static double getSquareRoot(double x) {
        double deltaThreshold = 1e-12;
        double min = 1.0;
        double max = x;
        double delta = x;
        double middle = -2.0;

        while (delta > deltaThreshold) {
            middle = (min + max) / 2;
            double square = middle * middle;
            delta = Math.abs((square / x) - 1);
            if (square > x) {
                max = middle;
            } else {
                min = middle;
            }

        }

        return middle;
    }

    public static double getSquareRootNewton(double x) {
        double deltaThreshold = 1e-12;
        double t = x;
        while (Math.abs(t - x / t) > deltaThreshold * x) {
            t = (t + x / t) / 2.0;
        }
        return t;
    }

    public static void main(String[] args) throws Exception {
        println(getSquareRoot(500));
        println(getSquareRootNewton(500));
    }
}