Re: float to string to float, with first float == second float
Rune Allnor wrote:
On 6 Okt, 11:16, Carsten Fuchs <CarstenFu...@T-Online.de> wrote:
Dear group,
I would like to serialize a float f1 to a string s, then unserialize s back to a float f2 again,
such that:
* s is minimal (use only the precision that is required)
and preferably in decimal notation,
* f1==f2 (exact same value after the roundtrip)
(The first property is for human readers and file size, the second is for data integrity.)
You should choose between *either* human readability *or*
data integrity. You can't have both.
You can have both. The seminal papers on this subject are:
Steele, Guy M. & Jon L. White, "How to Print Floating-point
Numbers Accurately", Proceedings of the ACM SIGPLAN '90
Conference on Programming Language Design and Implementation.
White Plains, New York, June 20-22, 1990.
Clinger, William D., "How to Read Floating-point Numbers
Accurately", Proceedings of the ACM SIGPLAN '90 Conference on
Programming Language Design and Implementation. White Plains,
New York, June 20-22, 1990.
And there's a followup:
Gay, David M., "Correctly Rounded Binary-Decimal and
Decimal-Binary Conversions", AT&T Bell Laboratories
Numerical Analysis Manuscript 90-10, November 30, 1990.
with an implementation that's available from netlib.
But the cost is sometimes high: it's not easy to implement, and you
occasionally have to break into unlimited precision integer math to get
the right answer.
The basic strategy is to write enough decimal digits to distinguish the
value being written from its two (binary) neighbors.
I vaguely recall that the C standard requires this round-trip behavior,
but I don't have a reference handy.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of
"The Standard C++ Library Extensions: a Tutorial and Reference"
(www.petebecker.com/tr1book)