%
% Newton 法
%
clear all; 
close all;

f  = @(x) x * exp(x) - 1;
df = @(x) exp(x) * (1 + x);

xt      = fzero(f,0.5);   % 精确解, 用于测试收敛阶 
itermax = 10;             % 最大迭代步数
tol     = 1e-12;          % 精度要求（函数值）

x0   = 0.5;           % 迭代初始值
err0 = abs(x0 - xt);  % 初始误差
fprintf('x0 = %.8f, f(x) = %.2e\n', x0, f(x0));
for k = 1 : itermax
    x = x0 - f(x0)/df(x0);
    err = abs(x - xt);
    fx  = f(x); 
    fprintf('k = %d, x = %.8f, fx = %.2e, err = %.2e, order = %.2f\n', ...
        k, x, fx, err, log(err)/log(err0));
    if (abs(fx) < tol), break, end
    x0 = x;
end

