Sqrt(x) II

Important Note:
1) Pay attention to the number that is less than 1.0, because x^0.5 will larger than x. So we need to always set the right side to be 1.0

2) For double, just let end - start less than 1e-12, which means end and start are almost the same. This will use to control the accuracy. 

public class Solution {
    /**
     * @param x a double
     * @return the square root of x
     */
    public double sqrt(double x) {
        // Write your code here
        double start = 0;
        double end = x;
        double eps = 1e-12;

        if (end < 1.0) {
            end = 1.0;
        }

        while (end - start > eps) {
            double mid = start + (end - start) / 2.0;
            //double mid = (end + start) / 2.0;
            if (mid * mid < x) {
                start = mid;
            } else {
                end = mid;
            }
        }
        
        return start;
    }
}

 

posted on 2017-05-11 05:27  codingEskimo  阅读(119)  评论(0)    收藏  举报

导航