Mail Archives: djgpp/2000/05/15/17:06:30
Andy17 wrote:
>I'm using DJGPP/RHIDE and am producing what appears to me a strange
>result when printing a float variable. After assigning a value and
>calling printf to display the result:
>
>profit = 2150.48;
>printf("Profit $%f\n", profit);
>
>it produces:
>
>Profit: $2150.479980
The problem is, that floating point values in DJGPP (and almost all
modern computers, pocket calculators are an exception) have a base of
two, and your "input" has a base of ten. In general, you cannot
represent a decimal value with a finite number of digits as an exact
floting point number. The problem is much like representing 1/3 in
base ten, where you need a infinite number of digits, 0.33333333333...
In base three, this would just be 0.1 (as 1/10 is 0.1 in base ten).
So if you have a finite number of digits, you have to round the result.
For 6 decimal digits, 1/3 may be 0.333333 and 2/3 0.666667. It turns
out, that the closest number to your input, that is an exact floating
point value of type float is 2150.479980468750000... The output
you got, is this number, correctly rounded to 6 places after the
decimal point.
That much said, if you use type double, your number will be printed,
as you expect. But the problem is still there, and it will show when
you print more digits. As a general rule, you can expect about 7-8
correct significant decimal digits for type float and about 16 significant
digits for type double.
--
Regards, Dieter Buerssner
- Raw text -