0
我一直在尋找用JavaScript編寫的巴比倫平方根的算法,並發現這個工作的解決方案:巴比倫平方根算法 - 初始估計值
function sqrt(num) {
var accuracy = 0.000001;
function isPrecise(estimation) {
if (Math.abs(Math.pow(estimation, 2) - num) < accuracy) {
return true
} else {
return false
}
}
function improvePrecision(estimation) {
return (estimation + (num/estimation))/2;
}
function iteration(estimation) {
if(isPrecise(estimation)) {
return estimation;
} else {
return iteration(improvePrecision(estimation));
}
}
return iteration(num);
}
,但我看不出哪裏是初始猜測(代碼 - estimation
)值被定義。那麼當第一次迭代沒有猜測值時它是如何工作的?其實這個值應該等於num
的說法。
將函數參數作爲第一個猜測輸入。這是它的來電者。 – duffymo
對於'num'的合理數字範圍,該實現看起來不錯。但我敢打賭,它會給很差的結果或無限期地運行非常小的數字(1e-20),非常大的數字(1e20),零或負數。 –