function x = mynewton2(f, x0, epsilon)
% 用 Newton 下山法求 f(x)=0 的近似根
%
% 调用方式: x = mynewton(f,x0,epsilon)
% f -- 函数文件(必须是符号函数)
% x0 -- 迭代初始点
% epsilon -- 精度要求
if ~isa(f,'sym')
fprintf('\n Error: f is not a symbolic function!\n'); return;
end
dfx = diff(f);
iter_max = 100; % 设置最大迭代步数
x(1) = x0;
fprintf('\n x(k+1) f(x(k+1)) \n');
for k = 1 : iter_max
fxk = subs(f,x(k));
if abs(fxk)<epsilon, break, end
dfxk = subs(dfx,x(k));
if dfxk==0, fprintf('\n Error: f''(%f)=0!\n',x(k)); return; end
dk = -fxk/dfxk; delta=1;
x(k+1) = x(k) + delta*dk;
while abs(subs(f,x(k+1))) >= abs(fxk)
delta = delta/2;
if delta<epsilon,
fprintf('\n Error: Delta=%g is too small!\n',delta), return;
end
x(k+1) = x(k) + delta*dk;
end
fprintf('k=%-3d %10.8e %10.8e \n',k,x(k+1),subs(f,x(k+1)));
end
x = x(k);
% END
来自:潘建瑜的个人网页
[ 本帖最后由 happy 于 2006-12-6 11:04 编辑 ] |