【发布时间】:2021-11-06 12:46:30
【问题描述】:
我正在编写一个小代码来使用张量流中的有限差分法计算四阶导数。如下:
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))
结果如下图:
但是,如果我使用基本相同的代码但只使用 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 = fourth_deriv(np.tanh(x), x)
plt.plot(test)
这给出了:
这里有什么问题?起初我在想点之间的间隔可能太小而无法给出准确的计算,但显然,如果 numpy 可以很好地处理它,情况并非如此。
【问题讨论】:
标签: python numpy tensorflow