求一個浮點數的平方根——牛頓迭代法

求一個浮點數的平方根——牛頓迭代法

public class CMath {
    private CMath() {}

    /**
     * Calculate the square root of a double floating-point number.
     *
     * @param d the double floating-point number
     * @return the square root
     */
    public static double sqrt(double d) {
        if (d < 0)
            return Double.NaN;
        double err = 1e-15;
        double t = d;
        while (CMath.abs(t - d / t) > err * t) {
            t = (d / t + t) / 2.0;
        }
        return t;
    }

    /**
     * Calculate the absolute value of a double floating-point number.
     *
     * @param d the double floating-point number
     * @return the absolute value
     */
    public static double abs(double d) {
        return (d < 0) ? -d : d;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章