我正在嘗試以迭代方式計算公式中的n:f = n^2,以便f接近 3,精度從底部算起 3 個小數位。為了說明,我在這里寫了一個成功完成我想要的代碼。這段代碼的一個問題是,我正在啟動外部腳本而不是 f=n^2,并且使用這種方法,整個迭代變得非常慢,因此無法使用。它需要太多的周期才能收斂到給定的精度。因此,我正在尋找更快的方法來實作收斂。我的意思是“更快”以更少的周期收斂。有人向我推薦了二進制搜索演算法,你能用這個小例子 f = n^2 來幫助創建它嗎?
這是我的代碼,它演示了我想要什么。
n = 1; % initial value
f=n^2; % function to calculate
tol = 3; % tolerance
accuracy = 0.0000001; % accuracy
while f <= tol
n = n accuracy;
f=n^2;
end
n = n-accuracy;
f=n^2;
disp(['n = ' num2str(n,10)])
disp(['f = ' num2str(f,10)])
更新:這是我為 Newton-Raphson 演算法設定函式及其導數的示例。不幸的是,它可能是不正確的,所以我想請你幫忙。
n = 7.76; % initial guess
f_error = [7.73 9 12.404 7.659 8.66];
df_error = diff(f_error)
xNew = n - f_error./df_error
uj5u.com熱心網友回復:
牛頓-拉夫森法
f_error(x) = x^(1/2) - N
f'_error(x) = (1/2)*x^(-1/2)
xNew = x - f_error(x)/f'_error(x)
repeat:
xNew = x - (x^(1/2) - N) / ((1/2)*x^(-1/2))
比嘗試掃描它們之間的所有浮點可表示值更快地接近目標值:
n = 3; % initial guess
nNew = n;
val = 3; % value
f=val^2; % function to calculate
accuracy = 0.0001; % accuracy
error = 10000;
count = 0;
while abs(error) > accuracy
nNew=n-(n^(1/2) - val)/((1/2)*n^(-1/2));
error = nNew-n
n=nNew
count = count 1
end
disp(['c = ' num2str(count,10)])
disp(['n = ' num2str(n,10)])
disp(['f = ' num2str(f,10)])
輸出:
c = 5 <--- only 5 iterations
n = 9
f = 9
您的方法未能在https://octave-online.net服務器的時限內完成計算:
n = 1; % initial value
f=n^2; % function to calculate
tol = 3; % tolerance
accuracy = 0.0000001; % accuracy
count = 0;
while f <= tol
n = n accuracy;
f=n^2;
count = count 1;
end
n = n-accuracy;
f=n^2;
disp(['c = ' num2str(count,10)])
disp(['n = ' num2str(n,10)])
disp(['f = ' num2str(f,10)])
輸出:
!!! OUT OF TIME !!!
c = 847309
n = 1.0847309
f = 1.176641126
它在 5 秒內僅移動了 0.1766,因此它至少需要 1-2 分鐘才能完成,而 Newton-Raphson 方法只需要 5 次迭代即可完成。由于舍入誤差,n=n accuracy 方法也不適用于大 n 值。如果下一個二進制可表示的 n 浮點值大于 n accuracy,則它會陷入無限回圈。
上面的 Newton Raphson 方法使用平方根。許多 x86 CPU 都有用于 sqrt 的 CPU 指令,因此它很可能被加速,但您也可以通過另一種 Newton-Raphson 方法找到平方根:
f_error(x) = x^2 - N
f'_error(x) = 2*x
xNew = x - f_error(x)/f'_error(x)
xNew = x - (1/2)*x - (1/2)*(N/x)
但它仍然有 N/x 的劃分。如果 CPU 沒有除法,那么您可以使用另一個 Newton Raphson:
f_error(x) = 1/x - N
f'_error(x) = -1/(x*x)
xNew = x - f_error(x)/f'_error(x)
xNew = x*(2-N*x)
將此應用于其他兩種方法將導致完全基于乘法的版本,并且可能會更慢,因為您需要迭代的三次冪,因此總共可能需要數百次迭代。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/477558.html
下一篇:使用for回圈的函式回傳不同的值
