% given a & b such that f(a)f(b)<0, find c in (a,b) such that f(c) = 0 a = 1; b = 2; ep = 10^-4; % the error tolerance max_iterate = 10000; % the maximum of the iteration steps if a >= b disp('a < b is not true. Stop!') return end fa = f(a); fb = f(b); if sign(fa)*sign(fb) > 0 disp('f(a0) and f(b0) are of the same sign. Stop!') return end c = (a+b)/2; it_count=0; %it_count is the iteration steps, starting with 0 while ( b-c > ep & it_count < max_iterate ) it_count = it_count + 1; fc = f(c); if sign(fb)*sign(fc) <= 0 a = c; fa = fc; else b = c; fb = fc; end c = (a+b)/2; end it_count format long e root = c error_bound = b-c function value = f(x) value = x^2 - 3; end