Re: float to string to float, with first float == second float
Rune Allnor wrote:
On 6 Okt, 14:22, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
On 6 Oct, 12:39, Rune Allnor <all...@tele.ntnu.no> wrote:
On 6 Okt, 11:16, Carsten Fuchs <CarstenFu...@T-Online.de> wrote:
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.
To demonstrate the point, try
-----------
#include <iostream>
int main()
{
float a=0.3;
double b = a;
std::cout << "a = " << a << std::endl;
std::cout.precision(12);
std::cout << "b = " << b << std::endl;
return 0;}
-----------
Output:
a = 0.3
b = 0.300000011921
There are two problems here:
1) Numbers that are exact in decimal notation
have no exact floating-point representation,
only an approximation.
try 0.5
Or 0.25, 0.125, 0.0625, etc., or *any combination thereof*. Then factor
in the exponents.
:-)
That's one of the few
*Few*? You're kidding, of course, aren't you? Using the IEEE
definition of "single precision float", there are *about* (2^32 - 2^24)
decimal values that can be represented *exactly*. Each of all the other
values (infinite number of them, of course) are rounded to one of the
*more than three billion* representations (my arithmetic may be off a tad).
> decimal numbers that can be represented
exactly on binary format. In fact, decimal numbers on the form
x = 2^n
where n is selected from a certain subset of integers, can be
represented exactly, as binary numbers. If the OP can accept
such a constraint on the decimal numbers he wants to work with,
then by all means, disregard what I said. But if he wants to
work with arbitrary numbers, he is in for trouble.
No, he is not "in for trouble". He just needs to realise that computer
representation of the floating point numbers have limitations, and *stay
within those limitations*. The computer *will* force the programmer to
"accept such a constraint". There are ways to overcome those, and they
are well-known, like the use of rational numbers, use of double
precision representation, or even arbitrary precision. Those methods
don't really *eliminate* the limitations, only *reduce* them. There is
still the limitation of the computing power (memory size is the most
significant one).
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask