js实现一个根号

使用二分法实现

function mySqrt (num){
    let n = Number(num);
    if(isNaN(n) || n < 0) return NaN;
    if(n == 0 || n == 1) return n;

    let up = n,
        down = 0,
        result = up / 2,
        last = result;
    do{
        if(Math.pow(result,2) > n){
            up = result;
        }else if(Math.pow(result,2) < n){
            down = result;
        }else{
            return result
        }
        last = result;
        result = (up + down) / 2;
    }
    while(Math.abs(result - last) >= Number.EPSILON);
    return last;
}

你可能感兴趣的:(js实现一个根号)