%
% 重根计算
%

clear all;
close all;


f = @(x) x^4 -4*x^2 + 4;
g1 = @(x) x-(x^2-2)/(4*x);
g2 = @(x) x-(x^2-2)/(2*x);
g3 = @(x) x-x*(x^2-2)/(x^2+2);

n = 10;
xt = sqrt(2);  % true solution
err = zeros(n+1,3); % 
fprintf('True solution: x=%.8f\n', xt);


x0 = 1.5;  % 迭代初始值
err(1,:) = [x0,x0,x0] - xt;
x1 = x0; x2 = x0; x3 = x0;
for k = 1 : n
    x1 = g1(x1);
    x2 = g2(x2);
    x3 = g3(x3);
    err(k+1,:) = abs([x1,x2,x3]-xt);
    fprintf('k=%2d, x1=%.8f, x2=%.8f, x3=%.8f\n', k, x1, x2, x3);
end

semilogy(1:n+1,err(:,1),'ob-', 1:n+1,err(:,2),'+r-', 1:n+1,err(:,3),'sg-');
legend('Newton', '改进Newton', 'Newton(\mu)')
