Frage

I'm trying to modify some library and I need to store a float value in a ptree. However when I retrieve the value it's different from what I've put in there. This doesn't happen with doubles. Example:

Ptree pt;

float f = 230518.391;
pt.put("float", f);
pt.put("double", (double) f)

cout << "f: " << f;
cout << "pt.float: " << pt.get<float>("float");
cout << "pt.double: " << pt.get<double>("double");

Output: f: 230518.391 pt.float: 230518.406 pt.double: 230518.391

What the hell is happening here?

War es hilfreich?

Lösung

Probably a combination of rounding "errors" & the compiler optimizing.. The rounding happens when the float is stored into the property tree..

However when you store a double the rounding doesn't happen. Now at the line pt.put("double", (double) f) the compiler might optimize the "f" away, and put the literal there. So the compiler doesn't use the rounded value. Similar for the first cout cout << "f: " << f; Here too the float is optimized away and the literal is put in its place.

EDIT: just tested it, can it be that the "rounded" value actually is "230518.906

this site might help with converting those numbers :).

Andere Tipps

You need to consider that float as a precision limited to somewhat around 7 digits. Therefore what you are seeing might be the nearest storable float value for your literal. In that case the other outputs might be influenced by compiler optimizations to get you the correct value (the compiler could omit converting f to double and simply put the literal in place.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top