Problem statement: . Write a MATLAB user-defined function that solves for a root
ID: 2262936 • Letter: P
Question
Problem statement: . 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 lf(x Use BisectionRoot to determine the root off(x) ps)-f(xNs), where f(xTs)-0 · x-2e-x. Start with a = 0 and b = 1.Explanation / Answer
%function xs=bisecroot(f,a,b)
% clc;
% clear all
f=@(x)x-2*exp(-x);
a=0; %initial condition
b=1;
eps_abs =2* 1e-8; % tolerence
eps_step = 1e-8;
n=1;
if sign(f(a))*sign(f(b)) >= 0
error('f(a)f(b)<0 not satisfied!') %ceases execution
end
N_max=500;
while (b - a >= eps_step || ( abs( f(a) ) >= eps_abs && abs( f(b) ) >= eps_abs ) )
xs = (a + b)/2; % midpoint
if ( f(xs) == 0 )
break;
elseif ( f(a)*f(xs) < 0 )
b = xs;
else
a = xs;
end
C(n)=xs;
err(n)=abs(b-a);
n=n+1;
if(n>N_max)
fprintf('Not converging ')
end
end
disp('num_iter x_value erorr')
disp('_______________________________________________________________________________')
for i=1:n-1
fprintf('%d %20f %20f ',i ,C(i),err(i))
end
disp('root is c')
xs
num_iter x_value erorr
_______________________________________________________________________________
1 0.500000 0.500000
2 0.750000 0.250000
3 0.875000 0.125000
4 0.812500 0.062500
5 0.843750 0.031250
6 0.859375 0.015625
7 0.851563 0.007813
8 0.855469 0.003906
9 0.853516 0.001953
10 0.852539 0.000977
11 0.853027 0.000488
12 0.852783 0.000244
13 0.852661 0.000122
14 0.852600 0.000061
15 0.852631 0.000031
16 0.852615 0.000015
17 0.852608 0.000008
18 0.852604 0.000004
19 0.852606 0.000002
20 0.852605 0.000001
21 0.852605 0.000000
22 0.852606 0.000000
23 0.852605 0.000000
24 0.852606 0.000000
25 0.852605 0.000000
26 0.852606 0.000000
27 0.852605 0.000000
root is c
xs =
0.852605499327183
>>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.