C ++: writing duplicates in a file with greater accuracy than the default.

I want to write duplicates to a file, but string casting reduces accuracy. Edit: I really don't quit, but put doubles in ostringstream.

Is there any other way than parsing each digit using modulation and division to record doubles with greater accuracy?

Edit: my application must be portable

Here is my current code:

std::string arraytocsv(double v[], int size) { std::ostringstream oss; for (int i = 0; i < size; i++) { oss << v[i] << ";"; } oss << std::endl; return oss.str(); } 

I had a precision () function, it works. Thanks

+4
source share
4 answers

You can use precision .

+9
source

After declaring a string stream, change its behavior:

 std::ostringstream oss; oss.flags (std::ios::scientific); oss.precision (std::numeric_limits<double>::digits10 + 1); 

The first call to oss.flags() forces C ++ I / O to use scientific notation in this stream of strings, even on something like pi. Print numbers smaller than 1.0 in fixed notation will lose precision when printing large numbers in fixed notations. Extreme bust.

The second call to oss.precision() tells C ++ I / O how many digits to print after the decimal point. Using the numbers 10 + 1, he reports that he is printing one extra digit; digits10 indicates how many digits the system can represent without loss of accuracy.

You will need #include because of this std::numeric_limits<double>::digits10 .

+3
source

Write it in binary format. This is not portable by default (in that the serialized format is architecture dependent)

instead

 double myvalue = 123.4; file << myvalue; 

do

 double myvalue = 123.4; file.write((const char*) &myvalue, sizeof(myvalue)); 

Of course, this assumes that you do not require people to read this (although using a UNIX tool like od , they can)

+1
source

If you work with only one system, you can write the actual binary data to a file, which will give you an exact copy. If you want to write to a text file, convert the binary to Base64 or something like that.

 std::ofstream myfile("file.bin"); double x; myfile.write(reinterpret_cast<char*>(&x), sizeof(x)); // later std::ifstream yourfile("file.bin"); double x; myfile.read(reinterpret_cast<char*>(&x), sizeof(x)); 

Optionally, encode the byte stream as base64. If you want to store long doubles and you are going to encode base64, note that the long double is usually only 10 bytes, so you can ignore the addition that it usually gets when serializing.

If you plan on exchanging data between different platforms, but all of which use IEEE floats, you should probably be more careful and document file format compliance. In this case, writing an ASCII string encoded with base64 will be more portable. To exchange data between platforms that do not all use the same binary floating-point representation, you will have to work even harder ...

0
source

All Articles