简体   繁体   中英

retaining the precison after reading and writing the double values to binary file

I am creating a binary file. the contents of the files are double values. When I extract the double values using a binary reader, some values after the decimal points are not matching

For ex: the value written to a file. -0.0139519833028316

Value extracted from a file. -0.0139519833028317

How I can avoid this kind of inconsistency?

aStreamWriter.WriteLine(double values);

//to read the data ,
BinaryReader aBinaryReader = new BinaryReader();
int points_length = CurveCount * VectorLength * 2 * VoxelIndex.Length * 2;
double[] points = new double[points_length];
for (int i = 0; i < points_length; i++)
    points[i] = aBinaryReader.ReadDouble();
for(int i =0; i < points_length; i++) {
    // then write the points values to a file
}

Is it truly an inconsistency? double is conceptually an aproximation to a real number. Is that digit significant given the error in the original measurement? Are they not truly the "same" number in this context?

Edit:

with your comment, the problem becomes obvious. StreamWriter is a text writer . The call to aStreamWriter.WriteLine(double) is writing text . Frankly, you were lucky to get anything back at all .


Original

Works fine:

    double d = -0.0139519833028316;
    byte[] raw;
    using (var ms = new MemoryStream())
    {
        using (var writer = new BinaryWriter(ms))
        {
            writer.Write(d);
        }
        raw = ms.ToArray();
    }
    double newVal;
    using(var ms = new MemoryStream(raw))
    using (var reader = new BinaryReader(ms))
    {
        newVal = reader.ReadDouble();
    }
    Console.WriteLine(newVal == d); // True

I suspect you're just seeing double rounding oddities, that are completely unrelated to the read/write code.

Basicly you have a problem with a double data type. Double is basicly making an aproximation of a number with a base of 2 (2^64). If there isnt an EXACT number that can be calculated (from base 10) then it picks closes number there is that can be saved as double.

If you need super precise way to save some number, save it as a string. Depend on math or what ever you need to do with a number, you can always write your own functions.

Simmilar stuff is happening with saving 'money value' as float in DB. they use money datatype due float isn't really a way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM