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:

The result looks like this:

Comparing forward, backward and central difference