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

问题描述 投票:4回答:1

我有一个在(xx,yy)meshgrid中定义的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()
python calculus
1个回答
4
投票

你需要两次打电话给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()

输出:

Result

© www.soinside.com 2019 - 2024. All rights reserved.