Write the function find_zero that is defined like this function x = find_zero(f,
ID: 3861978 • Letter: W
Question
Write the function find_zero that is defined like this function x = find_zero(f,x1,x2). The first input argument is special. It is a “function handle”. A function handle is gotten by typing @ and the name of any function. For example, x = find_zero(@sin,-1,1) will give f the function handle for MATLAB’s built-in sin function. Then, inside find_zero, the statement y = f(-1) would set y = sin(-1). Note that the @ sign is not used inside the function. Only the caller uses it. All other arguments to find_zero are scalar numbers, and x1 is less than x2. The goal of the function is to find an x that lies in the range from x1 to x2 such that after the command, y = f(x), is executed inside the function find_zero, y is approximately zero as defined by abs(y) < 1e-10. All you know about the function f is that it has one scalar input and one scalar output, and a plot of its values crosses the x-axis exactly once between x1 and x2, as, for example, in the figure. It is the responsibility of the caller to call the function with arguments that obey these rules.
0.5 -0.5 x1. x2Explanation / Answer
Matlab Function find_zero.m
function x = find_zero(f,x1,x2) % Function definition
y = f(x2); % Computing the function value at x = x2
while abs(y) > 1e-10 % exit loop if y approximatly equal to zero
x=x2-y*(x2-x1)/(y-f(x1)); % finding new x using secant method
x1=x2;%copy the value of x2 to x1
x2=x;% copy the value of x to x2
y = f(x2); % Computing the function value at new x
end % End of loop
end % End of program
Testing the function
f = @(x) -3.3*x.^3+2.5*x-0.6;
a =0;
b = 0.5;
x = find_zero(f,a,b)
x =
0.264397549547936
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.