% 
% Steffenson 迭代
%

clear all; 
close all;

f = @(x) 3*x^2 - exp(x);
g = @(x) 2*log(x) + log(3);

xt = fzero(f, [3,4]);  % 精确解, 用于测试收敛阶 
fprintf('True solution: x = %.8f\n\n', xt)


itermax = 30;    % 最大迭代步数
tol     = 1e-6;  % 精度要求（函数值）

% 不动点迭代 
fprintf('普通不动点迭代\n')
x    = 3.5;   % 迭代初始值
err0 = abs(x - xt);   % 初始误差
for k = 1 : itermax
    x   = g(x);
    err = abs(x - xt);
    fx  = f(x);
    fprintf('k = %2d, x = %.8f, fx = %.2e, err = %.2e, order = %.2f\n', ...
        k, x, fx, err, log(err)/log(err0)); 
    if (abs(fx) < tol), break, end
    err0 = err;
end
   
% Steffenson 迭代
x    = 3.5;          % 迭代初始值
err0 = abs(x - xt);  % 初始误差
fprintf('===================\n\n');
fprintf('Steffenson 迭代\n')
for k = 1 : itermax
    x1 = g(x); 
    x2 = g(x1);
    x = x - (x1-x)^2 / (x2-2*x1+x);
    err = abs(x - xt);
    fx  = f(x);
    fprintf('k = %2d, x = %.8f, fx = %.2e, err = %.2e, order = %.2f\n', ...
        k, x, fx, err, log(err)/log(err0)); 
    if (abs(fx) < tol), break, end
    err0 = err;
end