在Python中打包和解压缩二进制浮点数 [英] Packing and Unpacking binary float in python

查看:351
本文介绍了在Python中打包和解压缩二进制浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在进行二进制文件写入时,我在使用python进行二进制浮点数的打包和解压时遇到了一些麻烦。这里是我所做的:

$ $ p $ $ $ $ c $ import
$ bf = open('file.bin', '$'
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,)

额外数字是怎么回事?这是一个舍入错误?这是如何工作的?

解决方案

在大多数平台上,Python会调用一个 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)



<$> c $ c> float 结构格式只提供单精度(24位为重要精度)


I am having some trouble with packing and unpacking of binary floats in python when doing a binary file write. Here is what I have done:

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

The result I get is the following:

(1.2345600128173828,)

What is going on with the extra digits? Is this a rounding error? How does this work?

解决方案

On most platforms, Python floats are what C would call a double, but you wrote your data out as float instead, which has half the precision.

If you were to use double, you'd have less precision loss:

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

The float struct format offers only single precision (24 bits for the significant precision).

这篇关于在Python中打包和解压缩二进制浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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