精度差异:NumPy 对象数组与浮点数组
Precision Difference: NumPy Object Array vs. Float Array
我了解 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]
我是 运行 32 位 Python 在 64 位 Windows 上安装 2.7.12。
这只是您看到的显示格式问题。无论哪种方式,您实际上都没有得到更精确的数字;只是您设置的 precision=64
显示设置不适用于对象数组。它仅适用于浮点数据类型的数组。
如果多打印MyArray_precise
的内容:
print(format(MyArray_precise[0], '.64'))
# 0.442000000000000003996802888650563545525074005126953125
你会发现它实际上并不比另一个阵列好多少。
我同意你的浮动问题是显示问题,而不是精度问题。
但是长整数有一个不同的问题。 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
我了解 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]
我是 运行 32 位 Python 在 64 位 Windows 上安装 2.7.12。
这只是您看到的显示格式问题。无论哪种方式,您实际上都没有得到更精确的数字;只是您设置的 precision=64
显示设置不适用于对象数组。它仅适用于浮点数据类型的数组。
如果多打印MyArray_precise
的内容:
print(format(MyArray_precise[0], '.64'))
# 0.442000000000000003996802888650563545525074005126953125
你会发现它实际上并不比另一个阵列好多少。
我同意你的浮动问题是显示问题,而不是精度问题。
但是长整数有一个不同的问题。 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