6.4 Numerical Integration and Differentiation

Special functions are available for performing numerical integration and differentiation of expressions: int_dx() and diff_dx(). In each case, the ‘x’ may be replaced with any valid one-letter variable name, to integrate or differentiate with respect to that dummy variable.

The function int_dx() takes three parameters – firstly the expression to be integrated, which should be placed in quotes as a string, followed by the minimum and maximum integration limits. For example, the following would plot the integral of the function $\sin (x)$:

plot int_dt('sin(t)',0,x)

The function diff_dx() takes two obligatory parameters plus two further optional parameters. The first is the expression to be differentiated, which, as above, should be placed in quotes as a string, followed by the point at which the differential should be evaluated, followed by optional parameters $\epsilon _1$ and $\epsilon _2$ which are described below. The following example would evaluate the differential of the function $\cos (x)$ with respect to $x$ at $x=1.0$:

print diff_dx('cos(x)', 1.0)

Differentials are evaluated by a simple differencing algorithm, and a parameter $\epsilon $ controls the spacing with which to perform the differencing operation:

  \[  \left.\frac{\mathrm{d}f}{\mathrm{d}x}\right|_{x=x_0} \approx \frac{f(x_0+\epsilon /2) - f(x_0-\epsilon /2)}{\epsilon }  \]    

where $\epsilon = \epsilon _1 + x \epsilon _2$. By default, $\epsilon _1 = \epsilon _2 = 10^{-6}$, which is appropriate for the differentiation of most well-behaved functions.

Advanced users may be interested to know that integration is performed using the quad function of the integrate package of the scipy numerical toolkit for Python – a general purpose integration routine.