""" Use array slicing and math operations to calculate the numerical derivative of ``sin`` from 0 to ``2*pi``. """ from numpy import linspace, pi, sin, cos from pylab import * # number of grid points N = 100 # calculate the sin() function on evenly spaced data. x = linspace(0,2*pi,N) y = sin(x) print x.shape # calculate the derivative dy/dx numerically. # First, calculate the distance between adjacent pairs of # x and y values. dy = y[1:N]-y[0:N-1] #y[1:]-y[:-1] dx = x[1:N]-x[0:N-1] #x[1:]-x[:-1] # Now compute the incremental ratio as derivative values numerical_der = dy/dx # Assuming central differences, these derivative values # centered in-between our original sample points. xCenters = (x[1:]+x[:-1])/2.0 # analytical derivative in xCenters points analytical_der =cos(xCenters) # distances between analytical and numerical derivative distances = abs(analytical_der-numerical_der) figure() plot(xCenters,analytical_der) plot(xCenters,numerical_der,'r--') show() print 'Numerical vs Analytical derivative: max. distance -> ', distances.max() print 'Numerical vs Analytical derivative: avr. distance -> ', distances.mean()