Why does fread sometimes return incorrect values?
Ältere Kommentare anzeigen
I regularly use MATLAB to analyse data generated elsewhere. Most commonly, I work with int16s and single precision floats.
However, I recently needed to use (64-bit) doubles. Some values read back fine, but others don't.
For example, if in my C code, I generate and save this number to file:
double x = -3.0 * cos(M_PI * 3.0 / 8.0);
then MATLAB correctly reads back the value (approx) -1.1481 from the file. If I interpret the file as uint64, then both C and MATLAB agree that this is:
MATLAB: 1.3831e+19
C: 13831221214917623563
However, if in my C code, I generate and save this number to file:
double x = -3.0 * cos(M_PI * 5.0 / 8.0);
then MATLAB reads back -8.1120e+242 instead of (precisely) 1.148050297095269289827. Furthermore, MATLAB and C now disagree about the uint64 interpretation:
MATLAB: 1.7465e+19
C: 4607849178062847754 (= 0x3ff25e69fd02ff0a)
As shown in this online tool, 0x3ff25e69fd02ff0a is the correct hex representation of 1.148050297095269289827.
What am I doing wrong?
5 Kommentare
dpb
am 26 Mär. 2019
Have to see the actual code that wrote and read with, not just description. Attaching the file would also be wise.
Guillaume
am 26 Mär. 2019
Matlab never displays uint64 in scientific notation, so clearly you're not reading the numbers as uint64.
As dpb says, we'd have to see the code you use.
4607849178062847754 is indeed the uint64 representation of -3.0 * cos(M_PI * 5.0 / 8.0);
>> x = -3.0 * cos(pi * 5.0 / 8.0);
>> typecast(x, 'uint64')
ans =
uint64
4607849178062847754
Guillaume
am 26 Mär. 2019
by default, fread() casts to double. This isn't the problem.
Hum, it can be, any uint64 > 9007199254740992 (flintmax) may be rounded when converted to double.
Harry
am 27 Mär. 2019
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Low-Level File I/O finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!