简体   繁体   English

使用数组的二维求和-Python

[英]2d sum using an array - Python

I'm trying to sum a two dimensional function using the array method, somehow, using a for loop is not outputting the correct answer. 我试图使用数组方法求和一个二维函数,以某种方式,使用for循环不会输出正确的答案。 I want to find (in latex) $$\\sum_{i=1}^{M}\\sum_{j=1}^{M_2}\\cos(i)\\cos(j)$$ where according to Mathematica the answer when M=5 is 1.52725. 我想找到(在乳胶中)$$ \\ sum_ {i = 1} ^ {M} \\ sum_ {j = 1} ^ {M_2} \\ cos(i)\\ cos(j)$$,其中根据Mathematica,答案是当M = 5为1.52725时。 According to the for loop: 根据for循环:

def f(N):
s1=0;
for p1 in range(N):
    for p2 in range(N):
        s1+=np.cos(p1+1)*np.cos(p2+1)
        return s1
print(f(4))

is 0.291927. 是0.291927。

I have thus been trying to use some code of the form: 因此,我一直在尝试使用以下形式的代码:

def f1(N):
mat3=np.zeros((N,N),np.complex)
for i in range(0,len(mat3)):
    for j in range(0,len(mat3)):
        mat3[i][j]=np.cos(i+1)*np.cos(j+1)
        return sum(mat3)

which again 再次

print(f1(4))

outputs 0.291927. 输出0.291927。 Looking at the array we should find for each value of i and ja matrix of the form 查看数组,我们应该找到形式为i和ja的矩阵的每个值

mat3=[[np.cos(1)*np.cos(1),np.cos(2)*np.cos(1),...],[np.cos(2)*np.cos(1),...]...[np.cos(N+1)*np.cos(N+1)]]

so for N=4 we should have 所以对于N = 4我们应该有

mat3=[[np.cos(1)*np.cos(1) np.cos(2)*np.cos(1) ...] [np.cos(2)*np.cos(1) ...]...[... np.cos(5)*np.cos(5)]]

but what I actually get is the following 但是我实际得到的是以下内容

mat3=[[0.29192658+0.j 0.+0.j 0.+0.j ... 0.+0.j] ... [... 0.+0.j]]

or a matrix of all zeros apart from the mat3[0][0] element. 或除mat3 [0] [0]元素以外的全零矩阵。

Does anybody know a correct way to do this and get the correct answer? 有人知道这样做的正确方法并获得正确答案吗? I chose this as an example because the problem I'm trying to solve involves plotting a function which has been summed over two indices and the function that python outputs is not the same as Mathematica (ie, a function of the form $$f(E)=\\sum_{i=1}^{M}\\sum_{j=1}^{M_2}F(i,j,E)$$). 我选择此示例作为示例,因为我要解决的问题涉及绘制一个已在两个索引上求和的函数,而python输出的函数与Mathematica不同(即,形式为$$ f( E)= \\ sum_ {I = 1} ^ {M} \\ {sum_ J = 1} ^ {} M_2 F(I,J,E)$$)。

The return statement is not indented correctly in your sample code. 示例代码中的return语句未正确缩进。 It returns immediately in the first loop iteration. 它在第一个循环迭代中立即返回。 Indent it on the function body instead, so that both for loops finish: 在函数体上缩进它,以便两个for循环均完成:

def f(N):
    s1=0;
    for p1 in range(N):
        for p2 in range(N):
            s1+=np.cos(p1+1)*np.cos(p2+1)
    return s1

>>> print(f(5))
1.527247272700347

I have moved your code to a more numpy-ish version: 我已经将您的代码移到了更加麻木的版本:

import numpy as np

N = 5
x = np.arange(N) + 1
y = np.arange(N) + 1

x = x.reshape((-1, 1))
y = y.reshape((1, -1))

mat = np.cos(x) * np.cos(y)
print(mat.sum()) # 1.5272472727003474

The trick here is to reshape x to a column and y to a row vector. 这里的技巧是将x重塑为列,将y重塑为行向量。 If you multiply them, they are matched up like in your loop. 如果将它们相乘,它们就像在循环中一样被匹配。

This should be more performant, since cos() is only called 2*N times. 由于cos()仅被调用2 * N次,因此它应该具有更高的性能。 And it avoids loops (bad in python). 而且它避免了循环(在python中很糟糕)。

UPDATE (regarding your comment): 更新(关于您的评论):

This pattern can be extended in any dimension. 该模式可以在任何维度上扩展。 Basically, you get something like a crossproduct. 基本上,您会得到类似交叉产品的东西。 Where every instance of x is matched up with every instance of y, z, u, k, ... Along the corresponding dimensions. 其中x的每个实例与y,z,u,k,...的每个实例沿相应的维度匹配。

It's a bit confusing to describe, so here is some more code: 描述起来有点混乱,所以这里有更多代码:

import numpy as np

N = 5
x = np.arange(N) + 1
y = np.arange(N) + 1
z = np.arange(N) + 1

x = x.reshape((-1, 1, 1))
y = y.reshape((1, -1, 1))
z = z.reshape((1, 1, -1))

mat = z**2 * np.cos(x) * np.cos(y)

# x along first axis
# y along second, z along third
# mat[0, 0, 0] == 1**2 * np.cos(1) * np.cos(1)
# mat[0, 4, 2] == 3**2 * np.cos(1) * np.cos(5)

If you use this for many dimensions, and big values for N, you will run into memory problems, though. 但是,如果将其用于多个维度,并且将N设置为较大的值,则会遇到内存问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM