简体   繁体   English

精度差异:NumPy对象数组与浮点数组

[英]Precision Difference: NumPy Object Array vs. Float Array

I understand that the precision of a NumPy float array's element is limited by the machine epsilon. 我知道NumPy浮点数组元素的精度受计算机epsilon的限制。

However, I'm struggling to understand why specifying the array's datatype as a Python object, instead of as the default float, results in the array storing the precise value I feed it. 但是,我很难理解为什么将数组的数据类型指定为Python对象而不是默认的float会导致数组存储我提供给它的精确值。 Can someone please explain this behaviour? 有人可以解释一下这种行为吗?

The code below illustrates the rounding error associated with the float datatype, and the change in precision when using the object datatype. 下面的代码说明了与float数据类型相关联的舍入误差,以及使用对象数据类型时精度的变化。

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]

I'm running a 32-bit Python 2.7.12 installation on 64-bit Windows. 我正在64位Windows上运行32位Python 2.7.12安装。

That's just a matter of display formatting you're seeing. 这只是您看到的显示格式问题。 You're not actually getting a more precise number either way; 无论哪种方式,您实际上都没有得到一个更精确的数字。 it's just that the precision=64 display setting you set doesn't apply to object arrays. 只是您设置的precision=64显示设置不适用于对象数组。 It only applies to arrays of floating-point dtype. 它仅适用于浮点dtype的数组。

If you print more digits of the contents of MyArray_precise : 如果您打印MyArray_precise内容的更多位数:

print(format(MyArray_precise[0], '.64'))
# 0.442000000000000003996802888650563545525074005126953125

You'll see that it's not actually any better than the other array. 您会发现它实际上并没有比其他数组更好。

I agree that the issue you with floats is a matter of display, not precision. 我同意您的浮动问题是显示问题,而不是准确性问题。

But there is a different issue with long integers. 但是长整数存在另一个问题。 Python has a long integer type that does not have a numpy dtype. Python的长整数类型没有numpy dtype。

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

This is Py3. 这是Py3。 Py2 shows it as 12312312312311231231241241242342L 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM