【问题标题】:Numpy / C++ integers not promoted to python integers?Numpy / C++ 整数没有提升为 python 整数?
【发布时间】:2017-08-27 14:30:49
【问题描述】:

以下 Python 3.6 代码在 Windows 上运行:

print (111111, row [maxMins [deflectionIndex]])
print (222222, row [maxMins [deflectionIndex + 1]])
print (333333, row [maxMins [deflectionIndex]] - row [maxMins [deflectionIndex + 1]])
print (444444, 29697 - -23272)
print (555555, origRow.dtype)
print (666666, type (row [maxMins [deflectionIndex]])
a = row [maxMins [deflectionIndex]]
print  (777777, type (a))

其中row是从numpy数组origRow中获取的,如下:

    row = [origRow [0]]
    for sample in origRow [1:]:
        while sample == row [-1]:   # Avoid completely flat curve segments, since the max-min algorithm can't deal them
            sample += 0.000001 * (ev.random () - 0.5)
        row.append (sample)

打印:

111111 29697
222222 -23272
333333 -12567
444444 52969
555555 int16
666666 <class 'numpy.int16'> <class 'numpy.int16'>
777777 <class 'numpy.int16'>

我希望标有 333333 和 444444 的行显示相同的计算结果。

numpy 整数与 Python 整数的处理方式不同吗? 这意味着如果我首先将 numpy 数组元素分配给 Python 变量,语义会发生变化,因为它将被转换为 Python 无限长度整数? [编辑:不!]

很明显,它们存储为 C++ 固定长度整数,因此可以环绕。 但是如果 C++ 整数的数值范围太小,为什么不将它们提升为 Python 整数呢?

【问题讨论】:

  • 29697 - -23272 这是做什么的?我们可以用+替换它吗?
  • 它从 29697 中减去 -23272,就像上面那行一样,只是得到了完全不同的结果!
  • 好的,知道了。谢谢。
  • 行数组的 numpy dtype 是什么?
  • 它们没有区别对待,它们是不同的类型。 python 中的赋值不会触发任何转换或提升,它只是将名称绑定到对象。

标签: python numpy printing


【解决方案1】:

您正在溢出/包装,因为您的数组是 16 位值。

对于带符号的 16 位变量,值 52969 “环绕”为 -12567。当您使用 numpy 值(例如您的第 33333 行)进行计算时,您将获得包装后的结果。

当您使用 Python 类型(例如您的第 44444 行)进行计算时,您将获得全精度整数结果而不会溢出或换行。

【讨论】:

  • 非常感谢!即使我将它分配给 Python 标量变量,它也会保持类型 numpy.int16。如果我将它乘以 1,它就变成了 numpy.int32。很高兴知道!所以确实整个 numpy 类型系统与原生 Python 类型系统共存,这对我来说有一些意想不到的结果......
  • @Jacques,您不能为Python scalar variable 分配任何东西。 x = 111111 后跟 x = data[0] 不会更改原始标量。它改变了x 引用的内容。变量没有类型; type(x) 给出了 x 引用的对象的类型。
  • @hpaulj 对!有时我忘记了 Python 是多么合乎逻辑和常规......我仍然希望在 [] 中,索引操作会以某种方式转换值。但当然不可能,因为它会使 NumPy 中数组元素的简单分配变得非常缓慢。如果您仔细考虑,这一切都是非常合乎逻辑的。但我还是花了好几个小时才在我的应用程序中找到问题的原因。
猜你喜欢
  • 2018-02-27
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
  • 1970-01-01
  • 2022-01-20
  • 2017-07-01
相关资源
最近更新 更多