# Visualizing forward, backward and central difference

def f(k): return 2*k*np.log(k) - 4*k - 10 def forward_difference(seq): return [f(seq[i+2]) - 2*f(seq[i+1]) + f(seq[i]) for i, _ in enumerate(seq[:-2])] def backward_difference(seq): return [f(seq[i]) - 2*f(seq[i-1]) + f(seq[i-2]) for i, _ in enumerate(seq[2:])] def central_difference(seq): return [f(seq[i+1]) - 2*f(seq[i]) + f(seq[i-1]) for i, _ in enumerate(seq[1:-1])] import matplotlib.pyplot as plt import numpy as np np.random.seed(0) seq = np.arange(1,101) np.random.shuffle(seq) seq_range = range(len(seq) - 2) print(forward_difference(seq)) plt.plot(seq_range, seq[1:-1], 'k-', alpha = 0.5, label='original sequence') plt.plot(seq_range, forward_difference(seq), 'r-', lw=0.4, label='forward difference') plt.plot(seq_range, backward_difference(seq), 'g-', lw=0.4, label='backward difference') plt.plot(seq_range, central_difference(seq), 'b-', lw=0.4, label='central difference') plt.legend() plt.tight_layout() plt.show()

Here f is an arbitrary function. Higher order differences are also possible:

• fk+3 - 3*fk+2 + 3*fk+1 - fk
• fk+2 - 4*fk+1 + 6*fk - 4*fk-1 + fk-2

The result looks like this: