我怎样才能让 80 位浮点数在 numpy 中工作

how can i get 80 bit floats to work in numpy

在 numpy(或通常 python)中,我想利用 Intel x86 FPU 本机支持 80 位长双精度数据类型这一事实。我怎样才能做到这一点。在我的机器(intel core i7、macOS Catalina、python 3.8.1、numpy 1.19.1)上,以下尝试似乎失败了,因为似乎没有保留额外的数字:

>>> scalar = np.array([1.4756563577476488347],dtype=np.float64)
... with np.printoptions(precision=100,suppress=False):
...     print(scalar)
[1.475656357747649]


>>> scalar = np.array([1.4756563577476488347],dtype=np.float128)
... with np.printoptions(precision=100,suppress=False):
...     print(scalar)
[1.4756563577476489169]

>>> scalar = np.array([1.4756563577476488347],dtype=np.longfloat)
... with np.printoptions(precision=100,suppress=False):
...     print(scalar)
[1.4756563577476489169]

这似乎很奇怪,因为数据类型似乎就是我认为的那样(64 位与 80 位):

print(np.finfo(np.float64))

Machine parameters for float64
---------------------------------------------------------------
precision =  15   resolution = 1.0000000000000001e-15
machep =    -52   eps =        2.2204460492503131e-16
negep =     -53   epsneg =     1.1102230246251565e-16
minexp =  -1022   tiny =       2.2250738585072014e-308
maxexp =   1024   max =        1.7976931348623157e+308
nexp =       11   min =        -max
---------------------------------------------------------------

print(np.finfo(np.float128))

Machine parameters for float128
---------------------------------------------------------------
precision =  18   resolution = 1.0000000000000000715e-18
machep =    -63   eps =        1.084202172485504434e-19
negep =     -64   epsneg =     5.42101086242752217e-20
minexp = -16382   tiny =       3.3621031431120935063e-4932
maxexp =  16384   max =        1.189731495357231765e+4932
nexp =       15   min =        -max
---------------------------------------------------------------

是否与解析输入数字的能力有关?

问题是 Python 仅使用 64 位浮点数,而您正在将 Python 对象传递给 np.array

试试这个:

In [26]: scalar = np.array(['1.4756563577476488347'], dtype=np.float128)                                    

In [27]: with np.printoptions(precision=100, suppress=False): 
    ...:     print(scalar) 
    ...:                                                                                                   
[1.4756563577476488347]

通过使用字符串作为文字,创建 float128 对象的代码现在位于 NumPy 中,这将保留值的精度。