小编Tab*_*bin的帖子

使用 Tensorflow 中的有限差分计算四阶导数的准确性

我正在编写一个小代码来使用张量流中的有限差分方法计算四阶导数。如下:

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)

python numpy tensorflow

10
推荐指数
1
解决办法
522
查看次数

标签 统计

numpy ×1

python ×1

tensorflow ×1