fork download
  1. % Define the function g(x)
  2. g = @(x) x^2 - 2; % Example function (you can replace this with your function)
  3.  
  4. % Set initial guess
  5. x0 = 1; % Example initial guess (you can change this)
  6.  
  7. % Set tolerance and maximum number of iterations
  8. tol = 1e-6;
  9. max_iter = 1000;
  10.  
  11. % Initialize variables
  12. x_prev = x0;
  13. iterates = zeros(max_iter, 1); % To store the iterates
  14.  
  15. % Fixed-point iteration
  16. for k = 1:max_iter
  17. x_new = g(x_prev); % Update to the new value
  18. iterates(k) = x_new; % Store the iterate
  19.  
  20. % Check for convergence
  21. if abs(x_new - x_prev) < tol
  22. fprintf('Converged to %.6f after %d iterations.\n', x_new, k);
  23. break;
  24. end
  25.  
  26. % Update previous iterate
  27. x_prev = x_new;
  28. end
  29.  
  30. % If the loop completes without convergence
  31. if k == max_iter
  32. fprintf('Did not converge after %d iterations.\n', max_iter);
  33. end
  34.  
  35. % Plot the iterates to visualize convergence
  36. figure;
  37. plot(1:k, iterates(1:k), '-o');
  38. xlabel('Iteration');
  39. ylabel('Value of x');
  40. title('Fixed Point Iteration');
  41. grid on;
  42.  
Success #stdin #stdout 0.15s 57132KB
stdin
Standard input is empty
stdout
Converged to -1.000000 after 2 iterations.