I am writing a small code to calculate the fourth derivative using the method of finite differences in tensorflow. This is as follows:
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))
This results in the following graph:
However if I use essentially the same code but just using numpy, the results are much cleaner:
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)
Which gives:
What is the issue here? It was thinking at first that the separation between points could be too small to give an accurate computation, but clearly that's not the case if numpy can handle it fine.
from Accuracy in Calculating Fourth Derivative using Finite Differences in Tensorflow


No comments:
Post a Comment