Python:读取float80值

2024-04-28 02:35:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个10字节(80位)小端浮点值(或float80)的数组。如何在python3中读取这些值?在

struct不支持float80(可能是我不小心阅读了文档)。在

与包“struct”相同的包array不支持float80。在

numpy支持float128float96类型。这很好,但是在float80的尾部附加\x00来扩展它到float96或{}很难看,导入这个包需要很多时间。在

ctypes支持c_longdouble。它比numpy快很多倍,但是sizeof(c_longdouble)依赖于机器并且可以少于80位,在float80的尾部添加{}来扩展到{}也很难看。在

更新1:在mygist.github测试代码。 函数decode_str64很难看,但它可以工作。现在我在寻找正确的道路


Tags: 文档numpy字节数组arraystructpython3小心
3条回答

在4(x32)或16(x64)字节边界上添加填充,或者更确切地说,内存对齐浮动在4(x32)或16(x64)字节边界上,以避免与在x86 cpu上处理未对齐数据相关的性能损失。为了让你知道撞击的大小,some figures from Microsoft show ~2 times difference for DWORDs.

This layout is ingrained into the underlying C's ^{}不是numpy的发明,因此numpy不试图提供任何方法来仅提取/插入“重要”部分。在

因此,如果有没有填充的原始数据,手动添加填充看起来是一种方法。您可以通过直接写入底层缓冲区来加快该过程:

fi=np.finfo(np.longdouble)
assert fi.nmant==63 and fi.nexp==15, "80-bit float support is required"
del fi

len_float80=10    #no way to extract this from dtype/finfo
len_padded=np.dtype(np.longdouble).itemsize

f=open('float80.bin','rb')
f_items=os.stat(f.name).st_size//len_float80

n = np.empty(f_items,dtype=np.longdouble)

for i in xrange(f_items):
    raw=f.read(len_float80)
    n.data[i*len_padded:i*len_padded+len_float80]=raw

del f,i,raw,f_items

{或者更容易被维护的a5}在这里,这可能会损害代码的可维护性。在

或者,对于“交换”格式,您可以考虑使用不绑定到内部表示的格式,如^{}。在

让我用更合乎逻辑的方式重写我的答案:

ctypes c_longdouble依赖于计算机,因为longdouble float类型不是由C标准固定的,而是依赖于编译器:(但是对于高精度浮点,它仍然是您目前所能拥有的最好的类型。。。在

如果你打算用numpy,努比·隆杜比是你想要的,浮点数96或者numpy.float128都是很容易引起误解的名字。它们不表示96位或128位IEEE浮点格式。相反,它们指示基础long double类型使用的对齐位数。例如,在x86-32上,long double是80位,但是为了保持32位的对齐,long double被填充到96位,numpy将其称为float96。在x86-64上,longdouble再次是相同的80位类型,但是现在它被填充到128位以保持64位对齐,numpy将其称为float128。没有额外的精度,只有额外的填充。在

float80的末尾附加\x00来生成Float96是很难看的,但最后它只是,float96只是一个填充的float80numpy.longdoublefloat96或{},这取决于您使用的机器的体系结构。在

What is the internal precision of numpy.float128?

numpycan use 80-bit float if the compiler and platform support them

Whether [supporting higher precision] is possible in numpy depends on the hardware and on the development environment: specifically, x86 machines provide hardware floating-point with 80-bit precision, and while most C compilers provide this as their long double type, MSVC (standard for Windows builds) makes long double identical to double (64 bits). Numpy makes the compiler’s long double available as np.longdouble (and np.clongdouble for the complex numbers). You can find out what your numpy provides withnp.finfo(np.longdouble).

我检查了np.longdouble在PyPI是float64的股票numpy-1.11.1-win32.whl,在CentOS 6中是Gohlke's build和{}。在

相关问题 更多 >