Pascal Code
procedure
Bisection({function F(X:real):real:}
A,B,Delta:real;
var C,D:real;
var
A0,A1,A2,B0,B1,B2,C0,C1,C2:real;
var
Cond,K,KL,KR:integer);
const Big
= 1E5;
var Max:integer; YA,YB,YC:real;
begin
K := 0; KL := 0; KR
:= 0; YA := F(A); YB := F(B);
D := B - A;
Cond :=
0; {0:State
is iteration}
Max := 1 +
TRUNC((Ln(D) - Ln(Delta))/Ln(2));
if YA*YB > 0
then
Cond
:=
1; {1:Method
does NOT apply}
while (Cond=0) and
(K<MAX) do
begin
C
:= (A + B)/2.0; YC := F(C);
if
K = 0 then
begin A0
:= A; B0 := B; C0 := C; end;
if
K = 1 then
begin A1
:= A; B1 := B; C1 := C; end;
if
K = 2 then
begin A2
:= A; B2 := B; C2 := C; end;
if
YC = 0 then
begin
A
:= C; B := C;
Cond
:= 2; {2:A perfect ZERO was
found}
end
else
begin
if
YB*YC > 0 then
begin {Squeeze
from Right}
B
:= C; YB := YC; KR := KR+1;
end
else
begin {Squeeze
from Left}
A
:= C; YA := YC; KL := KL+1;
end;
end;
K
:= K+1;
end;
D := B - A;
if D < Delta
then
begin
if
Cond <> 2 then
Cond
:= 3; {3:Root is
within Tolerance}
if
(ABS(YA) > Big) and (ABS(YB) > Big) then
Cond
:= 4; {4:A Pole
of f(x) was found}
end;
end;
(c) John H. Mathews 2004