1.二分法求平方根:
function mySqrt (x) {
if (isNaN(x)) return NaN;
if(x===0 || x===1) return x;
let low=0,high=x, pivot=(low+high)/2,lastPivot;
do {
if(Math.pow(pivot,2)>x) {
high = pivot;
} else if(Math.pow(pivot,2)<x) {
low = pivot
} else {
return pivot
}
lastPivot = pivot;
pivot = (low+high)/2;
}
while(Math.abs(pivot-lastPivot) >= Number.EPSILON);
return pivot
}
console.log(Math.sqrt(10));
console.log(mySqrt(10));
2.切线逼近法
function mySqrt (x) {
if (isNaN(x)) return NaN;
if(x===0 || x===1) return x;
let val=x,last;
do{
last = val;
val = (val+x/val)/2
}while(Math.abs(val- last) >=Number.EPSILON);
return val;
}
console.log(Math.sqrt(10));
console.log(mySqrt(10));