fill in the gaps in the code function [xi,gi,n] = fixed_point(g,x0,tol) % Descri
ID: 673625 • Letter: F
Question
fill in the gaps in the code
function [xi,gi,n] = fixed_point(g,x0,tol)
% Description: Compute the fixed point of g(x) using the fixed point
% iteration.
%
% !!! NOTE: THIS CODE IS INCOMPLETE. PLEASE FILL IN THE GAPS !!!
%
% Inputs
%
% g: function handle, function whose fixed point we seek
%
% x0: double, initial guess for x
%
% tol: double, error tolerance (tol > 0)
%
%
% Outputs
%
% xi: double, (n+1,1) vector listing the iterates x0,x1,...,xn
%
% gi: double, (n+1,1) vector of function values g(x0),....,g(xn)
%
% n: int, number of fixed point iterations it took to reach convergence
%
%
%
% -------------------------------------------------------------------------
n_max = 100;
xi = zeros(n_max+1,1);
gi = zeros(n_max+1,1);
error = tol + 1; % initialize error
count = 0; % initialize iteration count
xnew = x0; % initialize x-value
while error > tol && count < n_max
count = count + 1;
% ---------------------------------------------------------------------
% Update iterate
% ---------------------------------------------------------------------
x0 = xnew;
xnew = % !!! your code here !!!
% Store iterates
xi(count+1) = xnew;
gi(count+1) = g(xnew);
% ---------------------------------------------------------------------
% Compute error
% ---------------------------------------------------------------------
error = %% !!! your code here !!!
end
n = count;
xi = xi(1:n+1);
gi = gi(1:n+1);
Explanation / Answer
%Solution:
function [xi,gi,n] = fixed_point(g,x0,tol)
% Description: Compute the fixed point of g(x) using the fixed point iteration.
% Inputs
% g: function handle, function whose fixed point we seek
% x0: double, initial guess for x
% tol: double, error tolerance (tol > 0)
%
% Outputs
% xi: double, (n+1,1) vector listing the iterates x0,x1,...,xn
% gi: double, (n+1,1) vector of function values g(x0),....,g(xn)
% n: int, number of fixed point iterations it took to reach convergence
% -------------------------------------------------------------------------
n_max = 100;
xi = zeros(n_max+1,1);
gi = zeros(n_max+1,1);
error = tol + 1; % initialize error
count = 0; % initialize iteration count
xnew = x0; % initialize x-value
while error > tol && count < n_max
count = count + 1;
% ---------------------------------------------------------------------
% Update iterate
% ---------------------------------------------------------------------
x0 = xnew;
xnew = g(x0)
% Store iterates
xi(count+1) = xnew;
gi(count+1) = g(xnew);
% ---------------------------------------------------------------------
% Compute error
% ---------------------------------------------------------------------
error =abs(xnew-x0)
end
n = count;
xi = xi(1:n+1);
gi = gi(1:n+1);
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.