我正在编写一个小代码来使用张量流中的有限差分方法计算四阶导数。如下:
def action(y,x):
#spacing between points.
h = (x[-1] - x[0]) / (int(x.shape[0]) - 1)
#fourth derivative
dy4 = (y[4:] - 4*y[3:-1] + 6*y[2:-2] - 4*y[1:-3] + y[:-4])/(h*h*h*h)
return dy4
x = tf.linspace(0.0, 30, 1000)
y = tf.tanh(x)
dy4 = action(y,x)
sess = tf.compat.v1.Session()
plt.plot(sess.run(dy4))
Run Code Online (Sandbox Code Playgroud)
结果如下图所示:
但是,如果我使用基本相同的代码但仅使用 numpy,结果会更清晰:
def fourth_deriv(y, x):
h = (x[-1] - x[0]) / (int(x.shape[0]) - 1)
dy = (y[4:] - 4*y[3:-1] + 6*y[2:-2] - 4*y[1:-3] + y[:-4])/(h*h*h*h)
return dy
x = np.linspace(0.0, 30, 1000)
test = …Run Code Online (Sandbox Code Playgroud)