Re: Can someone please explain - real numbers



On Thu, 9 Nov 2006 10:57:13 +0100, "Maarten Wiltink"
<maarten@xxxxxxxxxxxxxxxxxx> wrote:


It took some work, but here's a program that demonstrates the problem:

var X: Real;
begin
X:=0.2; { To start the recurring fraction immediately }
while True do begin
X:=16*X;
X:=X-3;
end;
end.

Sixteen times 0.2 equals 3.2, subtracting 3 should leave us with the
original 0.2. Ad infinitum. Right?

Okay...I had some time this evening so I played around with it, and
the solution is simple.

If the values derived purely from floating point calculations won't
give us the expected (and logical) results, then we (as programmers)
have to get creative in order to achieve those expected results.

==========================================
procedure TForm1.Button1Click(Sender: TObject);
var X: extended;
XasString: string;
a: integer;
begin
memo1.Clear;
X := 0.2;
XasString := FormatFloat('0.000000000000000000',x);
memo1.Lines.Add(XasString);
memo1.Lines.Add('X is equal to '+floattostrf(x,ffNumber,18,18));
for a := 1 to 16 do
begin
x := 16 * strtofloat(XasString);
memo1.Lines.Add('16 * x is currently
'+floattostrf(x,ffnumber,18,18));
x := x-3;
memo1.Lines.Add('X-3 is currently
'+floattostrf(x,ffnumber,18,18));
end;
memo1.Lines.Add('X is equal to '+floattostrf(x,ffNumber,18,18));
end;
==========================================

Same calculations as before...same 16 iterations of the loop.
But this time, the end result is exactly 0.2, which was exactly what
we started with, and the value of 16x is exactly 3.2 for every
iteration within the loop, which is exactly what it should be, and the
value of x-3 is exactly 0.2 (which is exactly what it should be).

Exactly. :-)
.