牛顿法迭代法 | matlab实现

function Newt(file_name, x0, xmin, xmax, n_points)
% file_name 是要进行迭代的函数
% x0 是选取的初始值
% xmin,xmax分别为图形横坐标的最小和最大值
% n_points 是自变量x的采样数

clf, hold off

wid_x = xmax - xmin;
dx = (xmax - xmin) / n_points;
xp = xmin: dx: xmax;
yp = feval(file_name, xp);
plot(xp, yp, 'r');
xlabel('x');
ylabel('f(x)');
title('Newton Iteration');
hold on

ymin = min(yp);
ymax = max(yp);
wid_y = ymax - ymin;
yp = 0.0 * xp;
plot (xp, yp); 
x = x0;
xb = x + 999;
n=0;
del_x = 0.001;
while abs(x - xb) > 0.000001;
if n>300
    break;
end
    y = feval(file_name, x);
    plot([x, x], [y, 0], 'black');
    plot(x, 0, 'o')
    fprintf('n = %3.0f,  x = %12.5e, y = %12.5e\n', n, x, y);
if n<4
    text(x, -wid_y/10, [num2str(n)]);
end
    y_driv = (feval(file_name, x+del_x)-y)/del_x;
    xb = x;
    x = xb-y/y_driv;
    n = n+1
    plot([xb, x], [y, 0], 'g')
end
plot([x, x], [0.05 * wid_y, 0.2 * wid_y], 'r'); 
text(x, 0.25 * wid_y, 'Final solution'); 
plot([x, (x - wid_x * 0.004)], [0.01 * wid_y, 0.09 * wid_y], 'r');
plot([x, (x + wid_x * 0.004)], [0.01 * wid_y, 0.09 * wid_y], 'r'); 
disp("牛顿迭代法结束")
end

你可能感兴趣的:(数值计算)