【问题标题】:Precision Difference: NumPy Object Array vs. Float Array精度差异:NumPy 对象数组与浮点数组
【发布时间】:2016-07-27 16:21:20
【问题描述】:

我了解 NumPy 浮点数组元素的精度受到机器 epsilon 的限制。

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

下面的代码说明了与浮点数据类型相关的舍入误差,以及使用对象数据类型时的精度变化。

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 安装。

【问题讨论】:

    标签: python numpy precision eps


    【解决方案1】:

    这只是您看到的显示格式问题。无论哪种方式,您实际上都没有得到更精确的数字。只是您设置的precision=64 显示设置不适用于对象数组。它仅适用于浮点 dtype 的数组。

    如果打印MyArray_precise的内容多位数:

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

    你会发现它实际上并不比另一个数组好。

    【讨论】:

      【解决方案2】:

      我同意您对浮点数的问题是显示问题,而不是精度问题。

      但是长整数有一个不同的问题。 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-09
        • 2011-09-22
        • 2021-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-22
        • 1970-01-01
        相关资源
        最近更新 更多