Python翻译C saxpy

时间:2016-06-24 14:26:20

标签: python c algorithm numpy

这是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

在我的代码中,它似乎工作正常(zarrayparray正在不断变化,因为它们位于while循环中。)

但接下来我做了:

btemp = beta / beta_prev
parray = saxpy(btemp, parray, zarray)

我的代码在循环中迭代了几次后失败了,它们不一样吗?

1 个答案:

答案 0 :(得分:2)

您将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'>