Find a root of equation \(e^{-x/2} + \sin(3x) = 1/2\) on the interval \([-1, 1.5]\) using bisection. (This is the function shown on Figure 7.3.2). The Matlab function
sign can be used to compare the signs of values.
Solution.
f = @(x) exp(-x/2) + sin(3*x) - 1/2;
a = -1;
b = 1.5;
if f(a)*f(b) >= 0
error('Not a bracketing interval');
end
while abs(b-a) >= 100*eps(a)
c = (a+b)/2;
if sign(f(c)) == sign(f(a))
a = c;
elseif sign(f(c)) == sign(f(b))
b = c;
else
break
end
end
fprintf('Found a root x = %.12g\n', (a+b)/2);
If the function has the same sign at both given endpoints, the bisection method cannot run, so the command
error is used to display a message and exit the program. This is a useful command to use when the computation has to be interrupted. The while loop runs until either the interval becomes small enough (length less than 100*eps(a)) or we accidentally reach \(f(c)=0\) so the loop stops.



