blog
blog copied to clipboard
平方根
function sqrt(num) {
function sqrtWrapper(min, max) {
let current = (min + max) / 2;
let nextMin = min, nextMax = max;
if (current * current > num) {
nextMax = current;
} else {
nextMin = current;
}
if (min === nextMin && max === nextMax) {
return current
}
else if (nextMax - nextMin < (1 / new Array(17).fill(10).reduce((a, b) => a * b, 1))) {
return current;
} else {
return sqrtWrapper(nextMin, nextMax);
}
}
return sqrtWrapper(0, num);
}
console.time();
console.log(sqrt(3));
console.timeEnd();