这是我写的一段代码:
import numpy as n
import cmath, math
v=[1,1,1,1,1][(1+0j), (0.30901699437494723+0.9510565162951536j), (-0.8090169943749477+0.5877852522924728j), (-0.8090169943749471-0.5877852522924736j), (0.3090169943749482-0.9510565162951533j)]
M=[[0]*5]*5
w=[0]*5
for a in range(0,5,1):
for b in range(0,5,1):
M[a][b]=cmath.exp(-2j*math.pi*a*b/5)
for k in range(0,5,1):
for i in range(0,5,1):
w[k]+=M[k][i]*v[i]
print M[0]
这是输出:
[(1+0j), (0.30901699437494723+0.9510565162951536j), (-0.8090169943749477+0.5877852522924728j), (-0.8090169943749471-0.5877852522924736j), (0.3090169943749482-0.9510565162951533j)]
但是,它应该是[1,1,1,1,1]。我试图找出代码中是否存在任何故障,但我无法做到。我的代码出了什么问题?
答案 0 :(得分:1)
矩阵M
的初始化出错了;这是你如何解决它:
M = [[0]*5 for i in range(5)]
# this would also work:
# M = [[0 for j in range(5)] for i in range(5)]
描述了问题,例如在this answer。
简短版本:矩阵中的所有行都指向同一个列表。其中一行的更改会反映在每一行中。
(顺便说一下; range(0, 5, 1)
通常只写为range(5)
)