Cogs and Levers A blog full of technical stuff

scipy

scipy is a specialist library for dealing with mathematical, science and engineering problems. According to their website:

The SciPy library, a collection of numerical algorithms and domain-specific toolboxes, including signal processing, optimization, statistics and much more.

The library itself is such a broad topic, so for the purposes of today’s article I just want to focus on a few items (from numpy) listed in their basic functions area covering polynomials and then finish up with the integration library.

Polynomials

A quick brush-up on some high school math (thanks wikipedia) tells us that a polynomial is an expression of more than two algebraic terms; these are normally variables (or indeterminates) and co-efficients.

Our polynomial with just one variable:

x² + 3x + 1

Let’s get scipy to represent this for us:

import numpy as np

p1 = np.poly1d([1, 3, 1])
print(p1)

This gives us an output of:

   2
1 x + 3 x + 1

Derivative

Lets derive this function, to find the formula that defines its instantaneous rate of change:

f(x)  = x² + 3x + 1
f'(x) = 2x + 3

We can get scipy to this for us using the deriv function:

print(p1.deriv())

Confirming everything for us, we now receive the derivative:

2 x + 3

Integral

We’ll integrate the same function now, providing us with the ability to calculate the area under the curve that the original polynomial would provide:

 f(x) = x² + 3x + 1
∫f(x) = x³ / 3 + (3x²) / 2 + x + C

We can simply use the integ function to do this for us, again:

print(p1.integ())

Providing us with the following answer:

        3       2
0.3333 x + 1.5 x + 1 x

General integration

Now that we’ve done some basic calculus with polynomials, we’ll get scipy to perform the integration for us. Using quad we specify the function that produces our values a maxima and minima value and then we’re given the integrated values.

We’ll simplify with .

import numpy as np
import scipy.integrate as integrate

f = np.poly1d([1, 0, 0])
result = integrate.quad(f, 0, 1)

We’re then given the following:

(0.33333333333333337, 3.700743415417189e-15)

To my eye, the answer is , and performing the basic subtraction I’m given: 0.33333333333332965. Pretty close?

This has been a really light-on tour of Scipy!