I wrote some parameters (all of type double
) to a file for use in performing some complex computations. I write the parameters to the files like so:
refStatsOut << "SomeParam:" << value_of_type_double << endl;
refStatsOut
is an ofstream
parameter. There are four such parameters, each of type double
. What I see as written to the file is different from what its actual value is (in terms of loss of precision). As an example, if value_of_type_double
had a value -28.07270379934792, then what I see as written in the file is -28.0727.
Also, once t开发者_开发技巧hese stats have been computed and written I run different programs that use these statistics. The files are read and the values are initially stored as std::strings
and then converted to double
via atof
functions. This results in the values that I have shown above and ruins the computations further down.
My question is this:
1. Is there a way to increase the resolution with which one can write values (of typedouble
and the like) to a file so as to NOT lose any precision?
2. Could this also be a problem of std::string
to double
conversion with atof
? If so, what other function could I use to solve this?
P.S: Please let me know in case some of the details in this question are not clear. I will try to update them and provide more details.
You can use the setprecision function.
ofstream your_file;
you can use your_file.precision(X);
The main difference between precision() and setPrecision() is that precision returns the current precision and setPrecision doesn't. Therefore, you can use precision like this.
streamsize old_precision = your_file.precision(X);
// do what ever you want
//restore precision
your_file.precision(old_precision);
a double
is basically a 64-bit integer, if you want a cheap way of writing it out, you can do something like this (note I'm assuming that your compiler uses long
for 64-bit ints)
double value = 32985.932235;
long *saveme = (long*)&value;
Just beware of the caveat that the saved value may not remain the same if loaded back on a different architecture.
精彩评论