Boost logo

Boost :

From: Edward Diener (eddielee_at_[hidden])
Date: 2006-03-14 15:58:16


John Maddock wrote:
>> This is a common cause of errors when using floating point values.
>> Writing a floating point value to a string representation, as are XML
>> values, and attempting to read that string representation back, does
>> not guarantee that the floating point value will remain exactly the
>> same
>> since there are a number of floating point values which have no exact
>> representation in the C++ floating point formats. That is simply
>> because
>> of the nature of floating point representation used in C++ and most
>> modern languages. After all, the number of floating point values
>> within
>> any range of numbers is infinite while the C++ floating point
>> representation cab not be. The only way to guarantee what you want for
>> floating point values is to write and read back to a binary
>> representation of the value.
>
> While it's true that some decimal values have no exact binary representation
> and vice-versa, I believe you *should* be able to write as a decimal string
> and read back in, and get the same value, provided:
>
> * You write enough digits to the file, numeric_limits<T>::digits + 2 seems
> to be enough, but I wouldn't want to guarantee that.
> * You're std lib is bug free: there certainly have been cases of std lib's
> that don't round-trip numbers in this way (I know because I've reported
> these as bugs!), getting round-trip binary-decimal-binary conversion right
> is actually pretty hard.
>
> The classic "What Every Computer Scientist Should Know About Floating-Point
> Arithmetic" at http://docs.sun.com/source/806-3568/ncg_goldberg.html fills
> in the details: 9 decimal digits are required for single precision reals,
> and 17 for double precision, a formula is also given that allows you to
> check that you have enough decimal digits for some p-digit binary number.
> It's also apparent that reading in a decimal number correctly requires
> extended precision arithmetic, so I suspect most problems are likely to
> occur when serialising the widest floating point type on the system. Even
> Knuth says "leave it to the experts" when discussing binary-decimal
> conversion BTW :-)

Thanks, John. I have to re-educate myself on my false presumption.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk