具有适当符号的 Numpy 八函数
Numpy eigh-function with proper signs
我想计算 python 中二阶导数矩阵的特征向量。根据数学,第一个向量应该等于 0 到 pi 之间的 sin 函数,第二个向量应该等于 0 到 2*pi 之间的 sin 函数。因此我的代码看起来像
import numpy as np
from matplotlib import pyplot as plt
from scipy import sparse
import scipy.integrate as integrate
import scipy.special as special
import scipy
def create_second_deriv(size, h):
delta_matrix_2_second_diff = (np.eye(size, dtype=np.float)*-2+np.eye(size, k=-1,dtype=np.float)*1+np.eye(size, k=1,dtype=np.float)*1)
delta_matrix_2_second_diff /= (h*h)
return -1*delta_matrix_2_second_diff
delta_x = 0.001
x = np.linspace(0, 1, (int)(1/delta_x))
delta_matrix = create_second_deriv(len(x), delta_x)
w, v = scipy.linalg.eigh(delta_matrix)
plt.plot(v.tolist()[0])
plt.show()
plt.plot(v.tolist()[1])
plt.show()
现在,我得到的输出是
作为第一个特征向量的图,并且
作为第二个特征向量的图。我已经知道不同值的符号是任意的,但在我的例子中,它们对以后的处理很重要。有没有办法 "flip" 符号使得结果值近似等于预期函数?在这种情况下,简单地使用 abs()
功能将无济于事。
There is a gotcha 与 scipy.linalg.eigh()
函数:
Be very careful using the eigh()
routine to get eigenvalues, though.
There's a "gotcha" buried in it.
The syntax is:
(eigenvalues, eigenvectors) = eigh(matrix)
This returns an array of eigenvalues and a 2D array of eigenvectors
(each eigenvector consists of many components).
And there's the gotcha. Let's say you want the n
th eigenvalue and
eigenvector. I would write:
eigenvalues[n]
eigenvectors[n]
And I would be horribly wrong. The eigenvectors and eigenvalues do
share an index, but the index on the eigenvector is SECOND column:
eigenvectors[:,n]
因此,您的代码的最后四行必须更改为:
plt.plot(v[:,0])
plt.show()
plt.plot(v[:,1])
plt.show()
我想计算 python 中二阶导数矩阵的特征向量。根据数学,第一个向量应该等于 0 到 pi 之间的 sin 函数,第二个向量应该等于 0 到 2*pi 之间的 sin 函数。因此我的代码看起来像
import numpy as np
from matplotlib import pyplot as plt
from scipy import sparse
import scipy.integrate as integrate
import scipy.special as special
import scipy
def create_second_deriv(size, h):
delta_matrix_2_second_diff = (np.eye(size, dtype=np.float)*-2+np.eye(size, k=-1,dtype=np.float)*1+np.eye(size, k=1,dtype=np.float)*1)
delta_matrix_2_second_diff /= (h*h)
return -1*delta_matrix_2_second_diff
delta_x = 0.001
x = np.linspace(0, 1, (int)(1/delta_x))
delta_matrix = create_second_deriv(len(x), delta_x)
w, v = scipy.linalg.eigh(delta_matrix)
plt.plot(v.tolist()[0])
plt.show()
plt.plot(v.tolist()[1])
plt.show()
现在,我得到的输出是
abs()
功能将无济于事。
There is a gotcha 与 scipy.linalg.eigh()
函数:
Be very careful using the
eigh()
routine to get eigenvalues, though. There's a "gotcha" buried in it.The syntax is:
(eigenvalues, eigenvectors) = eigh(matrix)
This returns an array of eigenvalues and a 2D array of eigenvectors (each eigenvector consists of many components).
And there's the gotcha. Let's say you want the
n
th eigenvalue and eigenvector. I would write:eigenvalues[n] eigenvectors[n]
And I would be horribly wrong. The eigenvectors and eigenvalues do share an index, but the index on the eigenvector is SECOND column:
eigenvectors[:,n]
因此,您的代码的最后四行必须更改为:
plt.plot(v[:,0])
plt.show()
plt.plot(v[:,1])
plt.show()