matlab中用牛顿法求方程的根
(2010-05-21 14:30:57)
标签:
matlab牛顿法线性方程课件杂谈 |
分类: Matlab |
代码如下:
function rtn=newton1(fx,dfx,x0,tol,N)
% Newton Method
% The first parameter fx is a external function with respect to viable x.
% The second parameter dfx is the first order diffential function of fx.
% x0 is initial iteration point.
% tol is the tolerance of the loop.
% N is the maximum number of iterations.
x=x0;f0=eval_r(fx);df0=eval_r(dfx);
n=0;
disp('
[
n
xn
xn+1
fn+1 ]');
while n<=N
x1=x0-f0/df0;
x=x1;f1=eval_r(fx);
X=[n,x0,x1,f1];
disp(X);
if
abs(x0-x1)
fprintf('The procedure was successful.')
return
else
n=n+1;
x0=x1;f0=f1;
end
end
if n==N+1
fprintf('the
method failed after N iterations. '),
end
保存为:newton1.m
运行如下:
>>fx='x-exp(-x)';
>>dfx='1+exp(-x)';
>>newton1(fx,dfx,.5,10^(-5),10)
[
n
xn
xn+1
fn+1 ]
0
0.5000
0.5663 -0.0013
1.0000
0.5663
0.5671 -0.0000
2.0000
0.5671
0.5671 -0.0000
3.0000
0.5671
0.5671 -0.0000
The procedure was successful.
最后求出的根为:0.5671
function rtn=newton1(fx,dfx,x0,tol,N)
% Newton Method
% The first parameter fx is a external function with respect to viable x.
% The second parameter dfx is the first order diffential function of fx.
% x0 is initial iteration point.
% tol is the tolerance of the loop.
% N is the maximum number of iterations.
x=x0;f0=eval_r(fx);df0=eval_r(dfx);
n=0;
disp('
while n<=N
end
if n==N+1
end
保存为:newton1.m
运行如下:
>>fx='x-exp(-x)';
>>dfx='1+exp(-x)';
>>newton1(fx,dfx,.5,10^(-5),10)
[
The procedure was successful.
最后求出的根为:0.5671