In: Computer Science
!!TRANSLATE TO MATLAB CODE!! INPUT: Function f, endpoint values a, b, tolerance TOL, maximum iterations NMAX CONDITIONS: a < b, either f(a) < 0 and f(b) > 0 or f(a) > 0 and f(b) < 0 OUTPUT: value which differs from a root of f(x) = 0 by less than TOL N ← 1 while N ≤ NMAX do // limit iterations to prevent infinite loop c ← (a + b)/2 // new midpoint if f(c) = 0 or (b – a)/2 < TOL then // solution found Output(c) Stop end if N ← N + 1 // increment step counter if sign(f(c)) = sign(f(a)) then a ← c else b ← c // new interval end while Output("Method failed.") // max number of steps exceeded
This pseudo code is of Bisection method of root solving.
%%xNs column gives the answer.
clc;clear all;
f=@(x) x-sin(x); %%Solving for the root of x-sin(x)=0 as test
case
a=0;b=2; imax=50;tol=0.01; %%Initial conditions
fa=f(a); fb=f(b);
if((fa*fb)>0) %%Checks if value has opposite signs then
proceeds
fprintf('Function has the same sign at the points');
else
disp('Iteration a b xNS f(xNS) Tolerance');
for(i=1:imax)
xNS=(a+b)/2; %Mid point
toli=(b-a)/2; %Computes tolerance
FxNs=f(xNS);
fprintf('%3i %11.6f %11.6f %11.6f %11.6f %11.6f
\n',i,a,b,xNS,FxNs,toli);
if(FxNs==0)
fprintf('Exact solution found at x=%11.6f',xNS);
break
end
if(toli<tol) %Breaks if tolerance level is reached
break;
end
if(i==imax)
fprintf('Solution not found in %i iterations',imax);
break
end
if(f(a)*FxNs<0)
b=xNS;
else
a=xNS;
end
end
end