views:

211

answers:

2
+3  Q: 

Trunc() function

Hi guys,

look the follow code, why the result of Trunc function is different?

procedure TForm1.Button1Click(Sender: TObject);
var
  D: Double;
  E: Extended;
  I: Int64;
begin
  D := Frac(101 / 100) * 100;
  E := Frac(101 / 100) * 100;
  I := Trunc(D);
  ShowMessage('Trunc(Double): ' + IntToStr(I));  // Trunc(Double): 1
  I := Trunc(E);
  ShowMessage('Trunc(Extended): ' + IntToStr(I)); // Trunc(Extended): 0
end;
+7  A: 

Formatting functions don't always display the actual numbers (data).
Real numbers and precision can be tricky.

Check out this code where I use more precision on what I want to see on the screen:

  D := Frac(101 / 100);
  E := Frac(101 / 100);
  ShowMessage(FloatToStrF(D, ffFixed, 15, 20));
  ShowMessage(FloatToStrF(E, ffFixed, 18, 20));

It appears that D is something like 0.010000000000 while E is like 0.00999999999.

Edit: Extended type has better precision than Double type. If we try to display the values of D and E with FloatToString() we'll probably get the same result, even though the actual values are not the same.

Nick D
+5  A: 

Note Nick D’s answer. He is right when saying that

It appears that D is something like 0.010000000000 while E is like 0.00999999999.

The answer however, is not in formatting function. This is how the float calculations are done. Computers simply do not understand float numbers (since there is infinite amount of numbers between 0 and 1, while computers operate on finite number of bits and bytes), and every Double or Extended variable in Delphi (and most other languages) is just an approximation (with some really rare exceptions).

You can read more of it on Wikipedia: Floating point and Fixed-point

smok1
smok1, we often examine float numbers without proper formatting parameters and we assume that we get the real values. That is of course wrong, since as you correctly mentioned, float numbers are an approximation of the actual numbers. +1
Nick D
+1 for explaining that computers store floating points as an approximation
Jeroen Pluimers
Not every floating number is an approximation. Negative powers of two and their sums (for example 0.5) are represented without approximation.
gabr
@gabr: added exceptions note inspired by your comment.
smok1