% Define the function g(x)
g = @(x) x^2 - 2; % Example function (you can replace this with your function)
% Set initial guess
x0 = 1; % Example initial guess (you can change this)
% Set tolerance and maximum number of iterations
tol = 1e-6;
max_iter = 1000;
% Initialize variables
x_prev = x0;
iterates = zeros(max_iter, 1); % To store the iterates
% Fixed-point iteration
for k = 1:max_iter
x_new = g(x_prev); % Update to the new value
iterates(k) = x_new; % Store the iterate
% Check for convergence
if abs(x_new
- x_prev
) < tol
fprintf('Converged to %.6f after %d iterations.\n', x_new
, k
); break;
end
% Update previous iterate
x_prev = x_new;
end
% If the loop completes without convergence
if k == max_iter
fprintf('Did not converge after %d iterations.\n', max_iter
); end
% Plot the iterates to visualize convergence
figure;
plot(1:k, iterates(1:k), '-o');
xlabel('Iteration');
ylabel('Value of x');
title('Fixed Point Iteration');
grid on;
JSBEZWZpbmUgdGhlIGZ1bmN0aW9uIGcoeCkKZyA9IEAoeCkgeF4yIC0gMjsgICUgRXhhbXBsZSBmdW5jdGlvbiAoeW91IGNhbiByZXBsYWNlIHRoaXMgd2l0aCB5b3VyIGZ1bmN0aW9uKQoKJSBTZXQgaW5pdGlhbCBndWVzcwp4MCA9IDE7ICAlIEV4YW1wbGUgaW5pdGlhbCBndWVzcyAoeW91IGNhbiBjaGFuZ2UgdGhpcykKCiUgU2V0IHRvbGVyYW5jZSBhbmQgbWF4aW11bSBudW1iZXIgb2YgaXRlcmF0aW9ucwp0b2wgPSAxZS02OyAKbWF4X2l0ZXIgPSAxMDAwOyAKCiUgSW5pdGlhbGl6ZSB2YXJpYWJsZXMKeF9wcmV2ID0geDA7Cml0ZXJhdGVzID0gemVyb3MobWF4X2l0ZXIsIDEpOyAlIFRvIHN0b3JlIHRoZSBpdGVyYXRlcwoKJSBGaXhlZC1wb2ludCBpdGVyYXRpb24KZm9yIGsgPSAxOm1heF9pdGVyCiAgICB4X25ldyA9IGcoeF9wcmV2KTsgJSBVcGRhdGUgdG8gdGhlIG5ldyB2YWx1ZQogICAgaXRlcmF0ZXMoa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