1. 程式人生 > 其它 >P8-x的平方根-牛頓迭代

P8-x的平方根-牛頓迭代

//x的平方根
/*
 * 在不使用sqrt(x)的情況下,得到x的平方根的整數部分
 * */
public class P8 {

    public static void main(String[] args) {
        System.out.println(newton(12));
    }

    //牛頓迭代
    /*
     * 跟微積分有關, y = x平方,是一個y軸對稱的二次函式
     * y/x = x,回想一下P3中12的(2*6) (3*4) (4*3) (6*2)
     * 關於 (根號12 * 根號12)對稱,y/x=根號12,x=根號12
     * 並且前後兩個數的平均值會比前後兩個數更接近結果
     * 如 2的平方=4,6的平方=36,它們的平均值4的平方=16,更接近12,
     * 即 y/x 和 x 的平均值會更接近結果 根號y即x  (y/x = x)
     *
     * 
*/ private static int newton(int y) { if(y == 0){ return 0; } return (int) sqrt(y, y); //第一個數是什麼沒有關係,正整數就可以,影響的是遞迴次數,會不斷的找均值最終趨向x } // public static double sqrt(double x, int y) { double res = (x + y / x) / 2; if (res == x) {
return x; //直到找到確切的根號y,即x } else { return sqrt(res, y); //不停找均值 } } }