function Bisect1(a,b,nmax) % Cheney/Kincaid 5th Ed., Page 94. % Bisection with a maximum number of iterations. % I used: % Bisect1(1.4,1.5,100) tic % This function will approx sqrt(2). % Inputs: a < sqrt(2) < b. % nmax = maximum number of iterations. % % This is called a function "handle". % This defines f(x). f = @(x) x^2 - 2; % Initialize the end points. u = f(a); v = f(b); % Cheney says to print them out. fprintf(' a = %20.17f\n',a); fprintf(' b = %20.17f\n',b); fprintf(' u = %20.17f\n',u); fprintf(' v = %20.17f\n',v); if (u*v)>=0 fprintf(' Poor choice of [a,b]: u*v is >=0.\n'); end % We will run nmax iterations (or fewer). for i=0:nmax % Calculate the midpoint of the current interval. % Calculate f at that point. c = (a + b)/2.; w = f(c); % If (w*u) is machine zero, then stop! if (w*u)==0. fprintf(' Iteration #%5.0f\n',i); fprintf(' Midpoint = %20.17f\n',c); fprintf(' f(c) = %20.17f\n',w); return; else if (w*u) < 0. % If w*u is neg. then redefine the right end % of the interval. b = c; v = w; else % w*u must be pos.; so redefine the left end % of the interval. a = c; u = w; end end end % Print the final value of c & f(c). fprintf(' Iteration #%5.0f\n',nmax); fprintf(' Midpoint = %20.17f\n',c); fprintf(' f(c) = %20.17f\n',w); toc