Content provided under a CC-BY license. Copyright 2014 David I. Ketcheson. %matplotlib inline import numpy as np import matplotlib.pyplot as plt x_values = (0,1,2,3,4) y_values = (0,1,8,27,64) plt.plot(x_values,y_values,'-o') plt.plot(x_values,y_values,'-o') plt.hold(True) plt.plot(x_values[2:4],y_values[2:4],'-r',linewidth=5) plt.plot(x_values,y_values,'-o') plt.hold(True) plt.plot(x_values[1:3],y_values[1:3],'-r',linewidth=5) plt.plot(x_values,y_values,'-ok') plt.hold(True) plt.plot((x_values[1],x_values[3]),(y_values[1],y_values[3]),'-r',linewidth=5) def f(x): return x**3 x = np.linspace(0,4) tangent = 8 + 12*(x-2) plt.plot(x,f(x),'k',linewidth=2) plt.plot(x_values[2:4],y_values[2:4],'-g',linewidth=3) plt.plot(x_values[1:3],y_values[1:3],'-b',linewidth=3) plt.plot((x_values[1],x_values[3]),(y_values[1],y_values[3]),'-r',linewidth=3) plt.plot(x,tangent,'--k',linewidth=3) plt.legend(['f(x)','Forward','Backward','Centered','Tangent'],loc='best') plt.axis((0.5,3.5,0,40)) x = 2. df = 12. for h in (0.1, 0.05, 0.025): forward = (f(x+h)-f(x))/h forward_error = forward - df print 'h: ', h, ' Error: ', forward_error