我想计算两个变量函数的导数
f(x,y) = exp(sin(sqrt(x^2+y^2)))
[对于1D案例减少到
f(x) = exp(sin(x))
在此帖Finding first derivative using DFT in Python下完全涵盖 使用傅立叶变换。
但是,与这个函数w.r.t到x和y变量的解析导数相比,我得到了错误的结果。以下是使用过的代码:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
def surface_plot3D(X,Y,Z):
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(-3., 3.)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink = 0.5, aspect = 5)
def funct(x,y):
return np.exp(np.sin( np.sqrt(x**2 + y**2) ))
N = 2**4
xmin=0
xmax=2.0*np.pi
step = (xmax-xmin)/(N)
xdata = np.linspace(step, xmax, N)
ydata = np.copy(xdata)
X,Y = np.meshgrid(xdata,ydata)
Z = funct(X,Y)
surface_plot3D(X,Y,Z)
plt.show()
vhat = np.fft.fft2(Z)
what = 1j * np.fft.fftfreq(N,1./N)
whax, whay = np.meshgrid(what, what)
wha_x = whax * vhat
w_x = np.real(np.fft.ifft2(wha_x))
wha_y = whay * vhat
w_y = np.real(np.fft.ifft2(wha_y))
w_tot = np.sqrt( w_x**2 + w_y**2)
surface_plot3D(X, Y, w_tot)
plt.show()
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
def surface_plot3D(X,Y,Z):
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(-3., 3.)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink = 0.5, aspect = 5)
def funct(x,y):
return np.exp(np.sin( np.sqrt(x**2 + y**2) ))
#derivative wrt x
def dfunct_x(x,y):
return np.exp(np.sin( np.sqrt(x**2 + y**2) )) * np.cos( np.sqrt(x**2 + y**2) ) * y/np.sqrt(x**2 + y**2)
#derivative wrt to y
def dfunct_y(x,y):
return np.exp(np.sin( np.sqrt(x**2 + y**2) )) * np.cos( np.sqrt(x**2 + y**2) ) * x/np.sqrt(x**2 + y**2)
N = 2**4
xmin=0
xmax=2.0*np.pi
step = (xmax-xmin)/(N)
xdata = np.linspace(step, xmax, N)
ydata = np.copy(xdata)
X,Y = np.meshgrid(xdata,ydata)
Z = funct(X,Y)
#calling the derivative function wrt x
df_x = dfunct_x(X,Y)
#calling the derivative function wrt y
df_y = dfunct_y(X,Y)
mag_df = np.sqrt(df_x**2 + df_y**2 )
surface_plot3D(X,Y,Z)
surface_plot3D(X,Y,mag_df)
plt.show()
vhat = np.fft.fft2(Z)
what = 1j * np.fft.fftfreq(N,1./N)
whax, whay = np.meshgrid(what, what)
wha_x = whax * vhat
w_x = np.real(np.fft.ifft2(wha_x))
wha_y = whay * vhat
w_y = np.real(np.fft.ifft2(wha_y))
w_tot = np.sqrt( w_x**2 + w_y**2)
surface_plot3D(X, Y, w_tot)
plt.show()