Matplotlib - 绘制具有相同维度的 2 个值时出错

Matplotlib - Error in plotting 2 values with same dimensions

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 = -1*((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
np.set_printoptions(linewidth=100)
Hamiltonian(1,0.5).real

哪个 returns 以下矩阵(为了清楚起见,我在下面尝试做的只是输入这个)

定义哈密顿量后,我想寻找作为 h 参数函数的熵。代码背后的物理原理对于此类问题无关紧要。

# von Neumann entropy as a function of h and beta - Complete
# Definition of a mixed state: [Thermal Density Matrix used]
h = np.arange(0,2.5,0.1)
beta = 2
for i in range(h.size):
    H = Hamiltonian(1.0, h[i] )
    rho_thermal = expm(-1.0 * beta * H)
    tr = np.trace(rho_thermal)
    rho_thermal = rho_thermal / tr
    np.set_printoptions(linewidth=100)
    eigvals_rho_thermal, eigvecs_rho_thermal = LA.eigh(rho_thermal)
    # Entropy
    s = 0.0
    for i in range(eigvals_rho_thermal.size):
        s += -1.0 * (eigvals_rho_thermal[i] * np.log(eigvals_rho_thermal[i]))
    print(s)
plt.plot(h,s)

我的问题是为什么会出现以下错误:

我的代码returns s 的 25 个值和 h 的 25 个值为什么不绘制它们?

您需要将在每个循环步骤中获得的 s 的值存储在某处,以便稍后能够为每个 h 绘制每个 s。通常,您可以稍微简化代码并使用函数而不是 for 循环。 这是我的做法。

import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import expm

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 = -1*((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

# von Neumann entropy as a function of h and beta - Complete
# Definition of a mixed state: [Thermal Density Matrix used]
def get_entropy(beta, h, alpha=1.0):
    H = Hamiltonian(alpha, h)
    rho_thermal = expm(-1.0 * beta * H)
    tr = np.trace(rho_thermal)
    rho_thermal = rho_thermal / tr
    eigvals_rho_thermal, eigvecs_rho_thermal = np.linalg.eigh(rho_thermal)
    # Entropy
    s = -np.sum(eigvals_rho_thermal*np.log(eigvals_rho_thermal))
    return s

h = np.arange(0,2.5,0.1)
beta = 2    
s = [get_entropy(beta, hi) for hi in h]
plt.plot(h,s)

plt.show()