Python 网格numpy的功能
我有一个问题,我想画一个矩阵的行列式作为参数的函数,所以我有一个脚本Python 网格numpy的功能,python,numpy,Python,Numpy,我有一个问题,我想画一个矩阵的行列式作为参数的函数,所以我有一个脚本 def f(x, y): DD = np.matrix([[0., 0.],[0., 0.]]) + 0.j omega = x + 1.j * y # set up dispersion matrix DD[0,0] = 1 + omega DD[1,0] = omega DD[0,1] = omega DD[1,1] = 1 - omega metric
def f(x, y):
DD = np.matrix([[0., 0.],[0., 0.]]) + 0.j
omega = x + 1.j * y
# set up dispersion matrix
DD[0,0] = 1 + omega
DD[1,0] = omega
DD[0,1] = omega
DD[1,1] = 1 - omega
metric = np.linalg.det(DD)
return metric
xx = np.arange(1., 2., 0.1)
yy = np.arange(1., 2., 0.1)
x, y = np.meshgrid(xx, yy)
FPlot = f(x, y)
plt.contourf(x, y, FPlot)
plt.show()
有一个类型错误,因为欧米茄是一个网格,我不能把它放到矩阵中或者计算行列式——numpy需要矩阵中的标量。要获得正确的网格和计算的行列式,最好的方法是什么 您可以使用
np.frompyfunc
:
import numpy as np
import matplotlib.pyplot as plt
def f(x, y):
DD = np.matrix([[0., 0.],[0., 0.]]) + 0.j
omega = x + 1.j * y
# set up dispersion matrix
DD[0,0] = 1 + omega
DD[1,0] = omega
DD[0,1] = omega
DD[1,1] = 1 - omega
metric = np.linalg.det(DD)
return metric
f = np.frompyfunc(f, 2, 1)
xx = np.arange(1., 2., 0.1)
yy = np.arange(1., 2., 0.1)
x, y = np.meshgrid(xx, yy)
FPlot = f(x, y)
plt.contourf(x, y, FPlot) # Note that this is only using the real part of FPlot
plt.show()
如果你有全新的numpy 1.8,你可以使用它的一个很酷的新功能:线性代数gufuncs。基本上,当您调用
np.linalg.det
时,它将为您传入的任何形状数组计算最后二维的行列式:
xx = np.arange(1., 2., 0.1)
yy = np.arange(1., 2., 0.1)
x, y = np.meshgrid(xx, yy)
omega = x + 1.j * y
dispersion_matrices = np.empty(omega.shape + (2, 2), dtype=omega.dtype)
dispersion_matrices[..., 0, 0] = 1 + omega
dispersion_matrices[..., 1, 0] = omega
dispersion_matrices[..., 0, 1] = omega
dispersion_matrices[..., 1, 1] = 1 - omega
FPlot = np.linalg.det(dispersion_matrices)
plt.contourf(x, y, FPlot.imag) # the part missing in unutbus's plot!
plt.show()
以前从未见过该功能,这就解决了它!谢谢