Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best method to read a double from a Binary file created in C?

Tags:

python

c

double

A C program spits out consecutive doubles into a binary file. I wish to read them into Python. I tried using struct.unpack('d',f.read(8))

EDIT: I used the following in C to write a random double number

r = drand48();
fwrite((void*)&r, sizeof(double), 1, data);

The Errors are now fixed but I cannot read the first value. for an all 0.000.. number it reads it as 3.90798504668055 but the rest are fine.

like image 220
gnosio Avatar asked Mar 10 '09 18:03

gnosio


1 Answers

I think you are actually reading the number correctly, but are getting confused by the display. When I read the number from your provided file, I get "3.907985046680551e-14" - this is almost but not quite zero (0.000000000000039 in expanded form). I suspect your C code is just printing it with less precision than python is.

[Edit] I've just tried reading the file in C, and I get the same result (though slightly less precision: 3.90799e-14) (using printf("%g", val)), so I think if this value is incorrect, it's happened on the writing side, rather than the reading.

like image 117
Brian Avatar answered Oct 08 '22 17:10

Brian