On 11/13/2012 8:28 AM, Marcin Lukasik wrote:
> On Tuesday, 13 November 2012 13:11:23 UTC, Ben Bacarisse wrote:
>>
>> The main benefit of using floating point is to gain range at the expense
>> of precision, but it is often used simply to have a way to represent
>> fractional numbers. When used for that purpose, the loss of precision
>> is just annoying, but C does not have an exact non-integer numeric type.
>
> Thank you Ben.
> But does this mean that VALUE(2) stores 300.029999 or 300.03?
> In other words do I loose precision by doing ((float[]) TST[i]) or by formatting it as %f in printf?
Both, probably. (Also, the word you want is "lose.")
Most systems nowadays store floating-point values in base two,
meaning that the number actually stored has the value N/D where
N and D are integers and D is a power of two. You can easily see
that no such N/D can be equal to 30003/100; it's exactly the same
problem familiar base-ten notation runs into with values like 22/7.
Most systems nowadays round the N of a `float' value to 24
base-two digits, just as you might round 22/7 to four base-ten
digits and get 3.143. Your `300.03' is probably 9831383/32768,
which is (if I haven't goofed) the nearest N/D such that N uses
only 24 bits and D is a power of two. The exact value of this
fraction is 300.029998779296875, closer than any other `float'
to the desired 300.03 but not exactly equal to it.
The "%f" conversion introduces a further approximation and
an additional error. Unadorned "%f" always prints six digits
after the decimal point, rounding the number as needed -- this
spares you from seeing horrors like "300.029998779296875". If
you know your numbers aren't good to six decimal places you can
use "%.2f" to get two places, or "%.5f" for five places, and so
on. Your `float' probably has 24 base-two digits, equivalent to
a little more than 7 decimal digits, so for values near 300 you
can't expect digits after the fourth decimal place to mean much.
If you were to round to four places with "%.4f" you'd probably
see a value you'd find less confusing.
Don't, by the way, make the mistake of thinking that because
a value is *stored* to seven-and-change decimal digits' precision
that it is *accurate* to that degree. If you weigh yourself in
pounds you'll probably get a three-digit number, so with seven
digits' precision you can tack on four decimal places, right?
How much faith should you put in that rightmost decimal place?
--
Eric Sosman
d