2013-04-23 103 views
4

我在执行二进制文件写入时在python中打包和解压二进制浮点数时遇到了一些麻烦。下面是我做了什么:在python中打包和解压缩二进制浮点数

import struct 

f = open('file.bin', 'wb') 
value = 1.23456 
data = struct.pack('f',value) 
f.write(data) 
f.close() 

f = open('file.bin', 'rb') 
print struct.unpack('f',f.read(4)) 
f.close() 

结果我得到的是以下几点:

(1.2345600128173828,) 

这是怎么回事与额外的数字?这是一个舍入错误?这个怎么用?

+1

是的,浮点数本质上是不精确的。 – 2013-04-23 09:16:35

+5

有关完整* why *的信息,请参阅[每位计算机科学家应了解的浮点算术知识](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html)。 – 2013-04-23 09:17:12

+2

您遇到的Python教程[总结表示问题](http://docs.python.org/2/tutorial/floatingpoint.html#representation-error)。 – 2013-04-23 09:20:28

回答

6

在大多数平台上,Python浮点数是C所称的double,但是您将数据写为float而不是精度的一半。

如果你使用double,你必须精确度损失少:

>>> data = struct.pack('d',value) 
>>> struct.unpack('d',data) 
(1.23456,) 
>>> data = struct.pack('f',value) 
>>> struct.unpack('f',data) 
(1.2345600128173828,) 

float结构格式只提供single precision (24 bits for the significant precision)

+0

这很有道理......如果我理解正确,那意味着浮点部分不会比0.8388607更精确。这使得它只有不到7个小数位?我明白,指数允许更广泛的数字范围。 – Wilsonator 2013-04-23 09:33:24

+0

另外我假设“(1.2345600128173828,)”只是显示比实际数据类型更精确的python打印函数呢? – Wilsonator 2013-04-23 09:34:28

+0

'0.8388607',你从哪里得到这个数字?打印功能没有显示“更精确”,它只是将存储的实际值转换为十位数。 – phant0m 2013-04-23 09:34:50