I have a 20x20 matrix C0 and a 1D array v0 of length 20. The elements in the matrix and the vector are both complex numbers. I want to multiply each i-th element in v0 with the i-th element in the j-th row of the matrix C0, and sum over them in python.
I tried to do this with two methods, one is making use of the matmul function in numpy, and one is by writing the for loops explicitly. The codes are as below:
Method 1
L2 = L//2 # L=20
ks = np.arange(0,L2)
g1 = np.zeros((len(ts),L2),dtype=complex) # len(ts)=20
for ik in range(L2):
kx = -np.pi+2*ik*np.pi/L2
v0 = np.array([-1*np.exp(-1j*kx*(r/2)) for r in range(L)])
g1[:,ik] = np.matmul(C0,np.transpose(v0))
Method 2
L2=L//2 # L=20
g2 = np.zeros((len(ts),L2),dtype=complex)
for it in range(len(ts)): # len(ts)=20
for ik in range(L2):
kx = -np.pi+2.0*np.pi*ik/L2
for r in range(L):
g2[it,ik] = g2[it,ik]-np.exp(-1j*kx*(r/2.0))*C0[it,jp]
I think the two codes are basically calculating the same thing. However, if I plot them out with the following code:
plt.figure()
plt.plot(np.real(g1[:,7]),'x')
plt.plot(np.real(g2[:,7]),'d')
plt.title('real part of g[:,7]')
plt.figure()
plt.plot(np.imag(g1[:,7]),'x')
plt.plot(np.imag(g2[:,7]),'d')
plt.title('imag part of g[:,7]')
The plot looks like
The real part of the g's agrees approximately, which I can understand that the slight deviation may due to some error accumulation in the for loop. However, for the imaginary part, g1 obtained from method 1 is very off from the g2 obtained from method 2. Any ideas on why is it so or if I have done anything wrong in the code?
Any help would be highly appreciated.
question from:
https://stackoverflow.com/questions/66059255/disagreement-in-matrix-vector-multiplications-with-complex-numbers-in-python 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…