急~ matlab newton 的問題
請問有大大可以幫忙解釋每一句的內容嗎 感謝
%This program is written for newton method
%iter is the number of times
%x0 is the inital x
%tol is the tolence
%The function is y(x)=x0.^2.*exp(-x0) ,dy(x)=2*x0*exp(-x0)-x0^2*exp(-x0)
function newton(x0,tol)
t=1;
err=1;
while err > tol
x(t,1)=x0;
y(t,1)=x0.^2.*exp(-x0);
dy(t,1)=2*x0*exp(-x0)-x0^2*exp(-x0);
x1=x0-y(t,1)/dy(t,1);
err(t+1,1)=abs(x0-x1);
x0=x1;
t=t+1;
end
fprintf('\n x ' )
fprintf('\n %f ',x)
2 則回答
最佳解答
err=1; 這邊好像有點問題
--------------------------------
這沒有問題
這是預先給一個err值 給任何值 只要大於tol即可
因為下一行指令 while err>tol
表示err必須大於tol才能執行下列迴圈
2007-11-02 23:36:14 補充:
前面有%符號的 都只是說明 不執行
%This program is written for newton method 牛頓法求根
%iter is the number of times 迭代次數iter
%x0 is the inital x 初始值x0
%tol is the tolence tol為允許誤差
%The function is y(x)=x0.^2.*exp(-x0) ,dy(x)=2*x0*exp(-x0)-x0^2*exp(-x0) 函數和他的微分
function newton(x0,tol) %定義函數名newton 輸入x0, tol
t=1; %給初始值
err=1; %給初始誤差為err=1
while err > tol %當 err>tol 時 執行下列到end之間的程式
x(t,1)=x0; %令 x(t,1)=x0(初始猜測值)
y(t,1)=x0.^2.*exp(-x0); %令y(t,1)為x0代入方程式
dy(t,1)=2*x0*exp(-x0)-x0^2*exp(-x0); %dy(t,1)為y的微分
x1=x0-y(t,1)/dy(t,1); %這是牛頓拉夫生法公式 利用迭代法求出新的x值x1 牛頓拉夫生法公式請參考數值分析課本
err(t+1,1)=abs(x0-x1); %求出新的x1後 求出與x0之差 令為err
x0=x1; %新的x1取代x0
t=t+1; %迭代次數加1
end %相對前面while的指令 (有while 就一定要有end)
fprintf('\n x ' ) %列印出x
fprintf('\n %f ',x) %列印出x的數值 以f格式
2007-11-02 23:48:00 補充:
一般我們函數的寫法不會使用上面這種寫法
函數中 大都不用 fprintf
你只需要將第一行
function newton(x0,tol)
改成
function x=newton(x0,tol)
拿掉最後2行指令
fprintf('\n x ' ) %列印出x
fprintf('\n %f ',x) %列印出x的數值 以f格式
----------------------
執行
x=newton(0,0.01)
即可
%This program is written for newton method牛頓法求根
%iter is the number of times迭代次數iter
%x0 is the inital x初始值x0
%tol is the tolence
%The function is y(x)=x0.^2.*exp(-x0) ,dy(x)=2*x0*exp(-x0)-x0^2*exp(-x0)函數和他的微分
function newton(x0,tol)函數名newton
t=1;
err=1; 這邊好像有點問題
while err > tol
x(t,1)=x0;
y(t,1)=x0.^2.*exp(-x0);
dy(t,1)=2*x0*exp(-x0)-x0^2*exp(-x0);這部分由牛頓法的公式來的
x1=x0-y(t,1)/dy(t,1);
err(t+1,1)=abs(x0-x1);
x0=x1;
t=t+1;
end
fprintf('\n x ' )
fprintf('\n %f ',x) 顯示出x值
另外應該還要有最多迭代幾次(因為牛頓法不一定會收斂)