函数未循环的图

时间:2018-10-03 18:43:11

标签: python-3.x numpy for-loop matplotlib

我正在尝试绘制h与eig_gs的关系图,但它仅返回一个值。首先,哈密顿量定义如下:

def Hamiltonian(alpha,h):

    Sx = np.array([[0,1],[1,0]])
    Sy = np.array([[0,-1j],[1j,0]])
    Sz = np.array([[1,0],[0,-1]])
    I  = np.array([[1,0],[0,1]])

    H = ( (alpha*np.kron(np.kron(Sx,Sx),I))
       + (alpha*np.kron(np.kron(Sy,Sy),I))
       + (alpha*np.kron(np.kron(I,Sx),Sx))
       + (alpha*np.kron(np.kron(I,Sy),Sy))
       + (h*np.kron(np.kron(I,Sz),I)) )

    return H

哪个返回一个我可以用于工作的8x8矩阵。我的问题是阻止我的代码循环遍历所有oh h而不仅仅是最后一个值的代码在哪里错?我尝试将H插入for循环内,但这不会更改值,并且我尝试编写为

H = Hamiltonian(1,h.size)

(在for循环内)但这不能解决问题

# Computation of eigenvalues from density matrix

h = np.array([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])
eig_gs = np.zeros(h.size, dtype = 'complex')

for i in range(h.size):
    H = Hamiltonian(1,h.size)
    eigvals, eigvecs = LA.eigh(H)

    # Density of the GS
    g_state = eigvecs[:,0]
    rho_gs = np.outer(g_state, g_state.conjugate())

    # Expectation value of the energy GS density matrix
    eig_gs[i] = np.trace(rho_gs.dot(H))

plt.plot(h, eig_gs.real)
plt.show()

result

如果将plt.plot放入for循环中,则会得到以下信息(没有意义):

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要将哈密顿量放入for循环中,并在计算哈密顿量时传递相应的h值。附加所有特征值后,可以将其绘制在for循环之外。下面的结果显示了通过解决本征值问题而获得的离散能谱。使用axhline

绘制的水平线可以最好地显示离散能级
for i in range(h.size):
    H = Hamiltonian(1,h[i]) # Update the Hamiltonian
    eigvals, eigvecs = LA.eigh(H)
    # Density of the GS
    g_state = eigvecs[:,0]
    rho_gs = np.outer(g_state, g_state.conjugate())
    # Expectation value of the energy GS density matrix
    eig_gs[i] = np.trace(rho_gs.dot(H))

for i in range(h.size):
    plt.axhline(eig_gs[i].real)

enter image description here