Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a MATLAB user-defined function that solves for a root of a nonlinear equat

ID: 2260461 • Letter: W

Question

Write a MATLAB user-defined function that solves for a root of a nonlinear equation f(x) =0 using the Bisection method. Name the function Xs BisectionRoot(Fun, a,b). The output argument Xs is the solution. The input argument Fun is a name for the function that calculates f(x) for a given x (it is a dummy name for the function that is imported in BisectionRoot);a and b are two points that bracket the root. The iterations should stop when the tolerance in fis smaller than 0.000001. The program should check if points a and b are on opposite sides of the solution. If not, the program should stop and display an error message Note The tolerance in f is If(xTs)-f(xNSL where f(xrs) = 0 Use BisectionRoot to determine the root of f(x) = x-2e-x. Start with a = 0 and b = 1 * XNS number of iterations =

Explanation / Answer

syms f x
eps =0.00001;
% Case a:
f=exp(x)-2;
[x_root_bisec,x_bisec,f_bisec]=bisection(0,1,f,eps);

disp(['x_exact=',num2str(log(2)),' x_bisection=',num2str(x_root_bisec)])
figure(1)
ylabel('error')
xlabel('iteration')

% Case b:

f=atan(x-1/sqrt(2));
[x_root_bisec,x_bisec,f_bisec]=bisection(0,1,f,eps);

disp(['x_exact=',num2str(log(2)),' x_bisection=',num2str(x_root_bisec)])

figure(2)
hold off
semilogy(abs(f_bisec),'r-')
ylabel('error')
xlabel('iteration')
%-------------------------------------------------------------

function [x_root,x_guess,f_guess]=bisection(x1,x2,fun,eps)

xh1=min([x1 x2]);
xh2=max([x1,x2]);
x_guess = [xh1 xh2];
f_guess = subs(fun,x_guess);
if (f_guess(1)*f_guess(2)) > 0
disp('wrong guess');
x_root=NaN;
return
end
if min(abs(f_guess)) < eps
[f_min,i_min] = min(abs(f_guess));
x_root=x_guess(i_min);
disp('excellent guess')
return
end
iter = 2;
check = logical(1);

while check
iter = iter +1;
x_guess(iter)=(xh1+xh2)/2;
f_guess(iter) = subs(fun,x_guess(iter));
if min(abs(f_guess)) < eps
[f_min,i_min] = min(abs(f_guess));
x_root=x_guess(i_min);
check = logical(0);
else
if f_guess(iter) < 0
xh1=x_guess(iter);
elseif f_guess(iter) > 0
xh2=x_guess(iter);
end
end
end
%----------------------------------------------------------

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote