% bisect_exa1.m % Find a root for f(x) = x^6-x-1 % function [c,err]=bisect_exa1(a,b,tol,maxitr) % Define a function f = @(x) x.^6-x-1; % Default tol=10^(-6), maxitr=100 if nargin==2, tol=10^(-6); maxitr=100; end if f(a)*f(b)>0 disp('f(a) and f(b) have same sign! Stop!'); return elseif f(a)==0 disp('a is a root!'); c = a; err = 0; return elseif f(b)==0 disp('b is a root!'); c = b; err = 0; return end fprintf('-------------------------------------------------------------------- \n') fprintf(' n a b c |b-c| f(c) \n') fprintf('-------------------------------------------------------------------- \n') n = 1; c = (a+b)/2; err = abs(b-c); fc = f(c); fprintf('%3.0f %12.8f %12.8f %12.8f %12.4e %12.4e \n',n,a,b,c,err,fc) % while (err>tol & n<=maxitr) if sign(f(b))*sign(f(c))==0 disp('c is a root! Stop!'); return elseif sign(f(b))*sign(f(c))>0 b = c; else a = c; end n = n+1; c = (a+b)/2; err = abs(b-c); fc = f(c); fprintf('%3.0f %12.8f %12.8f %12.8f %12.4e %12.4e \n',n,a,b,c,err,fc) end
|
|