阿涵

牛顿迭代法求整数的平方根

// 使用牛顿迭代法求整数N的平方根。

public class NewtonMethod {


    public static double sqrt(int n) {

        double x0 = n;

        while (x0 * x0 - n > 0.001) {

            x0 = (x0 + n / x0) / 2;

        }

        return x0;

    }


    public static void main(String[] args){

        System.out.println(sqrt(4));

        System.out.println(sqrt(2));

    }

}


评论