从C中创建的二进制文件中读取双精度的最佳方法是什么? [英] What is the best method to read a double from a Binary file created in C?

查看:87
本文介绍了从C中创建的二进制文件中读取双精度的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C程序将连续的double吐出到二进制文件中。我希望将它们读入Python。我尝试使用 struct.unpack('d',f.read(8))

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))

编辑:
我在C语言中使用以下命令编写了一个随机双精度数

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

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

错误现已修复,但我无法读取第一个值。对于所有的0.000 ..数字,它读为3.90798504668055,但是其余的都很好。

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.

推荐答案

我认为您实际上正在阅读编号正确,但显示感到困惑。当我从您提供的文件中读取数字时,我得到 3.907985046680551e-14 -这几乎但不是零(展开形式为0.000000000000039)。我怀疑您的C代码只是以比python更低的精度打印它。

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.

我刚刚尝试用C读取文件,但我得到了相同的结果结果(尽管精度稍差:3.90799e-14)(使用printf(%g,val)),所以我认为如果该值不正确,则发生在书写侧,而不是读取侧。

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.

这篇关于从C中创建的二进制文件中读取双精度的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆