lintcode586- Sqrt(x) II- medium

Implement double sqrt(double x) and x >= 0.

Compute and return the square root of x.

 Notice

You do not care about the accuracy of the result, we will help you to output results.

Example

Given n = 2 return 1.41421356

二分模板法,只不过从start + 1 < end 变为start + eps < end。 eps是比你要求的精度小一点的一个数,比如1e-12(10的-12次方)。

另一个是牛顿迭代法。数学上的, x_(k+1)=1/2(x_k+n/(x_k)) 迭代去算,精度不够就进入while就可以了。

九章解析:

// 二分浮点数 和二分整数不同
// 一般都有一个精度的要求 譬如这题就是要求小数点后八位
// 也就是只要我们二分的结果达到了这个精度的要求就可以
// 所以 需要让 right 和 left 小于一个我们事先设定好的精度值 eps
// 一般eps的设定1e-8,因为这题的要求是到1e-8,所以我把精度调到了1e-12
// 最后 选择 left 或 right 作为一个结果即可

public class Solution {
    /*
     * @param x: a double
     * @return: the square root of x
     */
    public double sqrt(double x) {
        // write your code here
        double eps = 1e-12;
        double start = 0;
        double end = x <= 1.0 ? 1.0 : x;
        
        while (start + eps < end){
            double mid = start + (end - start) / 2;
            if (mid * mid < x){
                start = mid;
            } else {
                end = mid;
            }
        }
        
        return start;
    }
}
原文地址:https://www.cnblogs.com/jasminemzy/p/7599831.html