Python构造虚数矩阵报警告ComplexWarning: Casting complex values to real discards the imaginary part

问题描述:我在构造哈密顿矩阵时是包含复数i的,调试的时候控制台报警告,

ComplexWarning: Casting complex values to real discards the imaginary part

代码和警告如下

T0 = np.kron(s0, M*sz) + t1_*np.eye(4, k=1) + t1_*np.eye(4, k=-1)
T0[0, 2] = t2_ * np.exp(-1j * phi)
T0[2, 0] = t2_ * np.exp(1j * phi)
T0[1, 3] = t2_ * np.exp(1j * phi)
T0[3, 1] = t2_ * np.exp(1j * phi)

Python构造虚数矩阵报警告ComplexWarning: Casting complex values to real discards the imaginary part_第1张图片

具体解释就是:(将复数转换为实数丢弃虚部)这样会使我们计算的数据产生错误或者丢失。

解决方案:构造0复数矩阵

利用矩阵的可加性,我们首先构造一个等量大小的0复数矩阵,即指定矩阵类型,假设我们的T0是4X4大小的矩阵:

T0 = np.zeros((4, 4), dtype=complex)

然后用T0与上面报错的矩阵 相加,过程如下

T0 = np.zeros((4, 4), dtype=complex)
T0 = T0 + np.kron(s0, M*sz) + t1_*np.eye(4, k=1) + t1_*np.eye(4, k=-1)
T0[0, 2] = t2_ * np.exp(-1j * phi)
T0[2, 0] = t2_ * np.exp(1j * phi)
T0[1, 3] = t2_ * np.exp(1j * phi)
T0[3, 1] = t2_ * np.exp(1j * phi)

至此我们的矩阵就被Numpy自动转化为复数类型的矩阵了。

你可能感兴趣的:(Python,Hamiltonian,python,矩阵,numpy)