gpt4 book ai didi

python - NumPy 具有重叠切片的就地运算

转载 作者:行者123 更新时间:2023-12-01 03:08:00 28 4
gpt4 key购买 nike

考虑这个不恰当的操作:

>>> b = numpy.asarray([1, 2, 3])
>>> b[1:] = b[1:] - b[:-1]
>>> b
array([1, 1, 1])

现在考虑就地操作:

>>> a = numpy.asarray([1, 2, 3])
>>> a[1:] -= a[:-1]
>>> a
array([1, 1, 2])

他们给出了不同的结果,这是我没想到的。

更新:这种行为似乎发生了变化;现在他们给出了相同的结果。

我假设 NumPy 会按照正确的顺序(向后)进行减法,这样它们就会给出与异位减法相同的结果。

我的问题是:这是 NumPy 的预期行为,还是一个错误,或者结果未定义?

最佳答案

此行为以前未定义,但 since NumPy 1.13.0 ,具有重叠输入和输出的操作现在的行为就像首先复制输入一样。引用发行说明:

Operations where ufunc input and output operands have memory overlap produced undefined results in previous NumPy versions, due to data dependency issues. In NumPy 1.13.0, results from such operations are now defined to be the same as for equivalent operations where there is no memory overlap.

Operations affected now make temporary copies, as needed to eliminate data dependency. As detecting these cases is computationally expensive, a heuristic is used, which may in rare cases result to needless temporary copies. For operations where the data dependency is simple enough for the heuristic to analyze, temporary copies will not be made even if the arrays overlap, if it can be deduced copies are not necessary. As an example,np.add(a, b, out=a) will not involve copies.

Here is the relevant issue on GitHub .

关于python - NumPy 具有重叠切片的就地运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43151152/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com