Program 1.1 Bisection Method Computes approximate solution of f(x)=0 Input: inline function f; a,b such that f(a)*f(b)<0, and tolerance tol Output: Approximate solution xc
0001 %Program 1.1 Bisection Method 0002 %Computes approximate solution of f(x)=0 0003 %Input: inline function f; a,b such that f(a)*f(b)<0, 0004 % and tolerance tol 0005 %Output: Approximate solution xc 0006 function xc = bisect(f,a,b,tol) 0007 if sign(f(a))*sign(f(b)) >= 0 0008 error('f(a)f(b)<0 not satisfied!') %ceases execution 0009 end 0010 fa=f(a); 0011 fb=f(b); 0012 k = 0; 0013 while (b-a)/2>tol 0014 c=(a+b)/2; 0015 fc=f(c); 0016 if fc == 0 %c is a solution, done 0017 break 0018 end 0019 if sign(fc)*sign(fa)<0 %a and c make the new interval 0020 b=c;fb=fc; 0021 else %c and b make the new interval 0022 a=c;fa=fc; 0023 end 0024 end 0025 xc=(a+b)/2; %new midpoint is best estimate