In: Computer Science
In MATLAB write a function secant.m to apply the secant method.
function [x,i] = secant(f, x0, x1, tol, maxiters) [x,i] = secant(f, x0, x1, tol, maxiters)
performs the secant method with f(x), starting at x_0 = x0 and x_1 = x1, and continuing until either |x_i+1 - x_i| <= tol, or maxiters iterations have been taken.
The number of iterations, i, is also returned. An error is raised if the first input is not a function handle. A warning is raised if the maximum number of iterations is reached without achieving the tolerance.
Test the function on the problem f(x) = 0.9 cos(x) - sqrt(x) = 0, with starting values x0 = 0 and x1 - 1, and a tolerance of 10^-8 and maxiters of 20.
Do not use previous answer on Chegg as it's not working
Thank you!
MATLAB code for the problem is provided below, please comment if any doubts related to program running or other quires related to this answer:
MATLAB code:
%Test code to define the function
%%function definition is at the end
%assign the given function
f = @(x)( 0.9*cos(x) - sqrt(x))
%set the inital values given in the question
x0 = 0;
x1 = 1;
%set the tolerance value
tol = 10^-8;
%set maximum iters value
maxiters = 20;
%execute the method using above values
[x, i] =secant(f,x0,x1,tol,maxiters)
%print the results
fprintf('The root, x = %f', x)
fprintf('f(x)= %f', f(x))
%%secant function definition
function [x,i] = secant(f,x0,x1,tol,maxiters)
%find the first assumption
root = (x0*f(x1) - x1*f(x0))/(f(x1) - f(x0));
%set the iteration count as 0
iterationCount = 0;
%the infinte while loop to repeat till
%root gets with in the tolerance or
%exceed the maximum iteration number
while (1)
x0 = x1;
x1 = root;
%%Check if the tolerance limit reached
if(abs(x0 - x1 )< tol)
break;
end
%find the next approximation
root = (x0*f(x1) - x1*f(x0))/(f(x1) - f(x0));
%increase the iteration count
iterationCount = iterationCount + 1;
%%terminate if not toleration limit
%reached with maximum iteration
%with warning
if(iterationCount == maxiters)
disp('Warning!!!maximum iteration limit reached')
break;
end
end
%assign the results
x=root;
i=iterationCount;
end
Output: