如何在Python中找到函数f(x,y)沿x和y方向的偏导数: del^2 f(x,y)/[del(x)][del (y)]

4

我有一个定义在(x,y)网格上的2D函数f(x,y)。我想通过数值方法得到它的偏导数,如下所示。请注意,np.gradient不能完成这项工作,因为它沿着每个轴返回一个向量场。

enter image description here

我该怎么做?以下是我的代码:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-5, 5, 0.1)
y = np.arange(-4, 4, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
f = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,f)
plt.show()

df=np.gradient(f,y,x) #Doesn't do my job
df=np.array(df)
print(df.shape)

# h = plt.contourf(x,y,df)   #This is what I want to plot.
# plt.show()
1个回答

5
你需要调用 np.gradient 两次:
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-5, 5, 0.1)
y = np.arange(-4, 4, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
f = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,f)
plt.show()

dfy = np.gradient(f, y, axis=0)
dfxy = np.gradient(dfy, x, axis=1)
print(dfxy.shape)
# (80, 100)

h = plt.contourf(x, y, dfxy)
plt.show()

输出:

结果


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接