matlab code Write the function find_zero that is defined like this function x =
ID: 3841242 • Letter: M
Question
matlab code
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 3. It is the responsibility of the caller to call the function with arguments that obey these rules.
Figure 3 Output plot for x1 and x2 (Hint: Remember to label your axis’s)
Here are two sample runs:
>> find_zero(@sin,-2.5,2.3) % as shown in the figure
ans =
-6.4000e-11
>> format long
>> find_zero(@cos,-2,1.3)
ans =
-1.570796326871000
note: i have to get same answer without any errors or warnings and thank you
0.5 0.5 x1 x2Explanation / Answer
function mid = find_zero(fun, x1, x2)
if fun(x1) * fun(x2) > 0
return; %probably no solution
end
if fun(x1) < 0 %we expect fun(x1) > 0 and fun(x2) < 0
t = x1;
x1 = x2;
x2 = t;
end
mid = (x1 + x2)/2; %find the mid mpoint and value at mid point
y = fun(mid);
while abs(y) >= 1e-10 %while more than threshold
if y > 0 %replace x1 if mid produces +ve value
x1 = mid;
else %replace x2
x2 = mid;
end
mid = (x1 + x2)/2;
y = fun(mid);
end
end
I hope this answer helps you. I tried my best to keep the answer as simple as possible. If you need any assistance on this please let me know. I shall try my best to resolve all your issue!
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.