【问题标题】:Numpy array, power operator, wrong value/signNumpy 数组,幂运算符,错误的值/符号
【发布时间】:2017-01-17 06:39:05
【问题描述】:

当我在 Ipython 上执行以下操作时:

test = np.array([1,2,3,4])
test**50

它返回:

array([          1, -2147483648, -2147483648, -2147483648])

同时具有错误的值和符号。任何线索为什么我可能会得到这个?

【问题讨论】:

  • Numpy 整数的范围有限。当你得到一个非常大的数字(例如,2**50)时,它会“环绕”并变成负数。这种现象称为溢出。与 Numpy 不同,Python 本身没有这个限制:4**50 是 1267650600228229401496703205376。
  • @DYZ ...更准确地说,如您所说,Numpy 类型受效率限制(如您所说,许多类型是有符号类型)。但是 Python 原生的整数对象会自动提升为大整数对象,防止溢出。具体来说,np.array() 构造函数会将 dtype 设置为可以处理提供的初始值的最小尺寸类型。您可以使用关键字参数(选项)dtype= 来覆盖它或“向上转换”类型。 test = np.array([1,2,3,4], dtype='int') 应该会更好。但仍然可能无法处理这种极端情况。
  • (特别是当我用 Python 2.7.17 和 Numpy 1.11.1 测试这个例子时,我得到了大整数的自动提升,显然,一切都很好,大约 test**31 ...但除此之外,操作会导致:RuntimeWarning:power遇到无效值)。因此,与对原生 Python 大整数的相同操作相比,如此大的幂运算的 Numpy 广播不需要完全透明)。 docs.scipy.org/doc/numpy/reference/arrays.dtypes.html

标签: python numpy ipython


【解决方案1】:

正如 cmets 中所提到的,发生这种情况是因为整数数据类型溢出。 Numpy 使用低级别 int 数据类型初始化数组,因为它适合您提供的数据。

test = np.array([1,2,3,4])
test.dtype
# dtype('int32')

test[0] = 2**31 - 1  # works
test[0] = 2**31      # OverflowError: Python int too large to convert to C long

使用 32 位有符号整数(在我的系统上),它可以保存 -2147483648 和 2147483647 之间的值。

您可以强制数组具有不同的数据类型,例如浮点数:

test = np.array([1, 2, 3, 4], dtype=float)
# test = np.array([1.0, 2.0, 3.0, 4.0])  # this is the same
test**50

# array([  1.00000000e+00,   1.12589991e+15,   7.17897988e+23, 1.26765060e+30])

这是一个list of data types,可以作为字符串传递给dtype 参数。

如果您想要 Python 的大整数而不是浮点精度,这也可以(性能警告):

test = np.array([1,2,3,4], dtype=object)
test**50

# array([1, 1125899906842624, 717897987691852588770249, 
#        1267650600228229401496703205376], dtype=object)

【讨论】:

    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 2011-10-29
    • 1970-01-01
    • 2014-09-05
    • 2019-10-06
    • 2012-03-03
    相关资源
    最近更新 更多