js實現sqrt開方函數(二分法)


每次取一半的數和當前值做對比,如果比當前值大:下次的起始值不變,末尾值減一半(起始值與末尾值的和的一半);如果比當前值小:下次的起始值加一半(起始值與末尾值的和的一半),末尾值不變;直到起始值與末尾值的差值在指定范圍內才結束,注意由於浮點數計算問題需要阻止死循環的情況(“起始值與末尾值的和的一半”與原來的值仍舊相同)
如1000:第一次的值為(0,1000)
1、 500*500        >1000  下一次用(0,500)
2、 250*250     >1000  下一次用(0,250)
3、 125*125              >1000        下一次用  (0,125)
4、 62.5*62.5            >1000        下一次用  (0,62.5)
5、 31.25*31.25        <1000        下一次用  (31.25,62.5)
6、 46.875*46.875   >1000         下一次用  (31.25,46.875)
...
...
...
 
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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM