Michael Vinther Guest
|
Posted: Mon Dec 08, 2003 10:34 pm Post subject: Rounding errors with the Extended type |
|
|
I just came across a very strange problem with the Extended type in
Delphi. When computing 0+A-A where A is of type Extended the result is
not always zero.
In FormCreate for my main form I do get zero as expected, but in some
other event handler, e.g. Button1Click, I get -1.225e-16 when A is set
to the Pi constant See the example code below. Note that
TForm1.FormCreate and TForm1.Button1Click contain EXACTLY the same
lines. If Extended is replaced by Double the result is zero both
times.
Why don't I get zero both times with Extended calculatios? Is there
anything I can do to fix it except for changing to the Double type?
Is it a problem with Delphi or with the CPU? The program was testet on
an Athlon XP running Win2k.
procedure TForm1.FormCreate(Sender: TObject);
var A, B : Extended;
begin
A:=Pi;
B:=0;
B:=B+A;
B:=B-A;
ShowMessage(FloatToStrF(B,ffGeneral,5,5)); // Displays 0
end;
procedure TForm1.Button1Click(Sender: TObject);
var A, B : Extended;
begin
A:=Pi;
B:=0;
B:=B+A;
B:=B-A;
ShowMessage(FloatToStrF(B,ffGeneral,5,5)); // Displays -1.225e-16
end;
|
|