Python numpy数组循环中的中心差分问题

Python numpy数组循环中的中心差分问题,python,arrays,numpy,Python,Arrays,Numpy,输入数组以供参考 u = array([[ 0., 0., 0., 0., 0.], [ 0., 1., 1., 1., 0.], [ 0., 1., 1., 1., 0.], [ 0., 1., 1., 1., 0.], [ 0., 0., 0., 0., 0.]]) 使用for循环的python函数 import numpy as np u = np.zeros(

输入数组以供参考

u = array([[ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  1.,  1.,  1.,  0.],
           [ 0.,  1.,  1.,  1.,  0.],
           [ 0.,  1.,  1.,  1.,  0.],
           [ 0.,  0.,  0.,  0.,  0.]])
使用for循环的python函数

import numpy as np
u = np.zeros((5,5))
u[1:-1,1:-1]=1
def cds(n):
    for i in range(1,4):
        for j in range(1,4):
            u[i,j] = u[i,j+1] + u[i,j-1] + u[i+1,j] + u[i-1,j]
    return u
上述函数cds(5)通过对循环使用提供以下结果

u=array([[  0.,   0.,   0.,   0.,   0.],
         [  0.,   2.,   4.,   5.,   0.],
         [  0.,   4.,  10.,  16.,   0.],
         [  0.,   5.,  16.,  32.,   0.],
         [  0.,   0.,   0.,   0.,   0.]])
使用numpy实现相同功能

def cds(n):
    u[1:-1,1:-1] =  u[1:-1,2:] +  u[1:-1,:-2] +  u[2:,1:-1] +  u[:-2,1:-1]
    return u
但对于相同的输入阵列(u),使用NUMPY的函数CD(5)提供不同的结果

u=array([[ 0.,  0.,  0.,  0.,  0.],
         [ 0.,  2.,  3.,  2.,  0.],
         [ 0.,  3.,  4.,  3.,  0.],
         [ 0.,  2.,  3.,  2.,  0.],
         [ 0.,  0.,  0.,  0.,  0.]])
出现此问题的原因是,python“for loop”在循环时会将每个u[i,j]值更新到现有的u数组,但“numpy”没有

我希望numpy得到与for循环相同的结果


在NUMPY有没有办法解决这个问题?请帮助我,提前谢谢…

您可能可以使用它,尽管涉及的索引数组和切片可能会变得混乱。这不是“numpy中的问题”。您试图使用numpys
add
运算符实现迭代算法(迭代的结果
n
取决于迭代的结果
n-1
),根据定义,该运算符不是迭代的。要么找到问题的非迭代解决方案,要么研究用于实现迭代算法的工具。