%The sequence of points that converges to the root is%generated via c=[a*f(b)-b*f(a)]/[f(b)-f(a)]
f = @(x)(x*cos(x)+1);
%% False position uses the regula falsi method to approximate a root of f(x) = 0% in the interval [a,b].%% f is an anonymous function representing f(x),% a and b are the limits of interval [a,b],% kmax is the maximum number of iterations (default 20),% tol is the scalar tolerance for convergence (default 1e-4),%% r is the approximate root of f(x) = 0,% k is the number of iterations needed for convergence.%
a=-2;
b=4;
tol = 1e-2;
kmax = 20;
c = zeros(1,kmax); % Pre-allocateif f(a)*f(b) > 0
r = 'failure';
returnend
disp(' k a b')
for k = 1:kmax,
c(k) = (a*f(b)-b*f(a))/(f(b)-f(a)); % Find the x-interceptif f(c(k)) == 0 % Stop if a root has been foundreturnend
fprintf('%2i %11.6f%11.6f\n',k,a,b)
if f(b)*f(c(k)) > 0 % Check sign changes
b = c(k); % Adjust the endpoint of intervalelse a = c(k);
end
c(k+1) = (a*f(b)-b*f(a))/(f(b)-f(a)); % Find the next x-interceptif abs(c(k+1)-c(k)) < tol, % Stop if tolerance is met
r = c(k+1);
breakendend
fx = f(r);
fprintf('r = %11.6f\n', r);
fprintf('k = %11.1f\n', k);
mp = linspace(-2,4);
fp = arrayfun(f,mp,'UniformOutput',false); %func(mp);
fp = cat(1, fp{:});
hold on
plot(mp,fp),grid
plot(r,fx,'.','MarkerSize',20)
hold off
k a b
1 -2.000000 4.000000
2 1.189493 4.000000
3 1.189493 2.515720
4 1.960504 2.515720
r = 2.073843
k = 4.0
%Bisection method%Step 1: Choose lower xl and upper xu guesses for%the root such that the function changes sign%over the interval. This can be checked by ensuring%that f(xl)*f(xu) < 0.%Step 2: An estimate of the root xr is determined%by xr = (xl + xu)/2%Step 3: Make the following evaluations to determine%in which subinterval the root lies:%(a) If f(xl)f(xr) < 0, the root lies in the lower%subinterval. Therefore, set xu 5 xr and return to step 2.%(b) If f(xl)f(xr) > 0, the root lies in the upper%subinterval. Therefore, set xl 5 xr and return to step 2.%(c) If f(xl)f(xr) = 0, the root equals xr; terminate the computation.%Example