function demo2_1b; % the REALISTIC bisection method % solve f(x)=0 on [A,B] % eps=0.00001; % initial interval for sin(x) %A=1; %B=4; % initial interval for 3x-e^x A=1; B=2; % a=A; b=B; p=(a+b)/2; %% set up a counter to count the number of iterations i=1; % MAIN LOOP if (f(a)*f(p))>0 & (f(a)*f(p))>0 fprintf(1,'Error: no root in the given interval A: %6.2f B:%6.2f \n', A, B); a=b; p=[]; else while (abs(f(p))>eps) & (abs(b-a)>eps) & (i < 100) if (f(a)*f(p))<0 b=p; end if (f(b)*f(p))<0 a=p; end p=(a+b)/2; i=i+1; end %% To display all decimals, switch default print formatting to ''long'' format long %%%%% fprintf(1,'Number of iterations: %1i Solution found: %10.8f \n', i, p); % compare with the true solution for sin(x) %pi %abs(pi-p) end function y=f(x); %y=sin(x); y=1;