算法——二分法实现sqrt

public class Solution {
    public double mySqrt(double n, double accuracy) {
        double mid = n/2.0;
        double left = 0.0;
        double right = n;
        double temp;
        while (left<right) {
            temp=(mid-n/mid)*mid; // 这里是防止int越界,相当于mid^2-n
            if (temp >0 && temp<accuracy) {
                return mid;
            }else if(mid > n/mid){
                right = mid;
            }else{
                left = mid;
            }
            mid = (left+right)/2.0;
        }
        return -1d;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.mySqrt(2, 1e-2));
    }
}

 

posted @ 2019-05-12 17:33  高圈圈  阅读(338)  评论(0编辑  收藏  举报