精度差异:NumPy对象阵列与浮点阵列

时间:2016-07-27 16:21:21

标签: python numpy precision eps

据我所知,NumPy浮点数组元素的精度受机器epsilon的限制。

但是,我很难理解为什么将数组的数据类型指定为Python对象而不是默认的浮点数会导致数组存储我提供的精确值。有人可以解释一下这种行为吗?

下面的代码说明了与float数据类型相关的舍入错误,以及使用object数据类型时的精度变化。

import numpy as np

np.set_printoptions(precision=64)

MyArray = np.empty(2)
MyArray.fill(0.442)
print(MyArray)

# [ 0.442000000000000003996802888650563545525074005126953125
#   0.442000000000000003996802888650563545525074005126953125]

MyArray_precise = np.empty(2, dtype = object)
MyArray_precise.fill(0.442)
print(MyArray_precise)

# [0.442 0.442]

我在64位Windows上运行32位Python 2.7.12安装。

2 个答案:

答案 0 :(得分:3)

这只是你看到的显示格式问题。无论如何,你实际上并没有获得更精确的数字;只是您设置的limit 1显示设置不适用于对象数组。它仅适用于浮点dtype数组。

如果您打印precision=64的内容的更多数字:

MyArray_precise

你会发现它实际上并不比其他阵列更好。

答案 1 :(得分:0)

我同意浮动的问题是显示问题,而不是精确问题。

但长整数存在不同的问题。 Python有一个长整数类型,没有numpy dtype。

In [87]: x=12312312312311231231241241242342
In [88]: x
Out[88]: 12312312312311231231241241242342

这是Py3。 Py2将其显示为12312312312311231231241241242342L

In [90]: np.array([x])
Out[90]: array([12312312312311231231241241242342], dtype=object)
In [91]: np.array([x],int)
....
OverflowError: Python int too large to convert to C long
相关问题