我想用Python计算二维函数的一阶导数。为此,我写了以下脚本:
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import scipy.sparse as scspar
r_num = 10000
r_vec = np.linspace(-10, 10, r_num)
X_mat, Y_mat = np.meshgrid(r_vec, r_vec)
x_square = lambda X, Y: np.exp(-np.power(X, 2)/2-np.power(Y, 2)/2)
dh = abs(r_vec[1]-r_vec[0])
A = (np.eye(r_num)*(-30)+np.eye(r_num, k=-1)*(16)+np.eye(r_num, k=1)*(16)-np.eye(r_num, k=2)-np.eye(r_num, k=-2))/(12*dh*dh)
C = (np.eye(r_num)*(-30)+np.eye(r_num, k=-1)*(16)+np.eye(r_num, k=1)*(16)-np.eye(r_num, k=-2)-np.eye(r_num, k=2))/(12*dh*dh)
B = scspar.csc_matrix((np.eye(r_num)*-30+np.eye(r_num, k=-1)*16+np.eye(r_num, k=1)*16-np.eye(r_num, k=-2)-np.eye(r_num, k=2))/(12*dh*dh))
T = x_square(X_mat, Y_mat)
plt.imshow(A-B)
plt.show()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X_mat, Y_mat, T*B+(T.transpose()*B).transpose())
plt.show()
现在矩阵A
和{
与
T*A+(T.transpose()*A).transpose()
结果发生了显著变化。为什么?在
如果它们是相同的,它们应该有相同的结果。因此,你可以断定你在某个地方犯了错误。在
从scipy docs:
实际上,文档告诉我们不要在这些稀疏矩阵上使用numpy函数,而是使用specialized functions from scipy对稀疏矩阵进行操作。在
相关问题 更多 >
编程相关推荐