You are on page 1of 1

>> f = inline('x*cos(x)+1'); >> ezplot(f,[-2 4])

2 1.5 1 xcos(x) + x 0.5 0 -0.5 -1 -1.5 -2 -2.5 -2 -1 0 1 x 2 3 4 root

function [c k] = MyBisection(f, a, b, tol) % % MYBISECTION Uses the Bisection iterative procedure to approximate a root of % equation f(x) = 0 on the interval [a,b]. % % [c k] = MyBisection(f, a, b, tol) where % % f is an inline function representing f(x) in the equation f(x)=0. % a and b are the limits of interval [a,b]. % tol is the scalar tolerance for convergence (default 1e-4). % c is the approximate root of f(x) = 0. % k is the required number of iterations. % if nargin < 4, tol = 1e-4;end N =1+fix((log(b-a)-log(tol))/log(2)); if f(a)*f(b)>0 c = 'failure'; return end for k=1:N c=(a+b)/2; if f(c)==0 return end if f(b)*f(c)>0 b=c; else a=c; end if b-a<tol,return end end c = 'failure'; >> [c k] = MyBisection(f, -2, 4) c = 2.0740 k = 16

You might also like