Closed. This question is off-topic. It is not currently accepting answers. Learn more。
想改进这个问题吗?Update the question所以堆栈溢出的值小于aa>。
这是C代码:
btemp = (*beta)/(*beta_prev);
for (k=0; k<xsize*ysize; k++) {
parray[k] = zarray[k] + btemp*parray[k];
}
我在python中执行以下操作:
def saxpy(a, x, y):
return np.array([a * xi + yi for xi, yi in zip(x, y)], np.float32)
#...
btemp = beta / beta_prev
ptemp = saxpy(btemp, parray, zarray)
parray[:] = ptemp
在我的代码中,它似乎工作得很好(
zarray
和parray
不断变化,因为它们在while循环中)。但我会:
btemp = beta / beta_prev
parray = saxpy(btemp, parray, zarray)
我的代码在循环中迭代了几次后就失败了,它们不一样吗?
最佳答案
您将parray[:] =
更改为仅parray =
,这是不等价的。前者在元素的基础上分配parray
的内容,如果parray
与赋值的右侧不属于同一类型,这是一个重要的区别。
考虑两种情况:
>>> xs = [1, 2, 3, 4]
>>> xs[:] = tuple(2 * x for x in xs)
>>> xs
[2, 4, 6, 8]
>>> type(xs)
<class 'list'>
>>> xs = [1, 2, 3, 4]
>>> xs = tuple(2 * x for x in xs)
>>> xs
(2, 4, 6, 8)
>>> type(xs)
<class 'tuple'>
09-05 14:20