2.1. The NumPy library#

Python is designed to be a simple all purpose programming language to serve the needs of a wide variety of users. This is great as it means its easy to learn and use, however it also means that it does not have functions to perform the mathematical operations that we will be needing. Fortunately, we can import libraries which are a collection of objects (constants, commands and functions) into our programs so that we can use these to perform certain tasks.

One of the most useful Python libraries is NumPy library (pronounced Num-Pie) which contains a range of functions useful for scientific computing and working with arrays. To import the NumPy library we use the import keyword. Run the following common in the console.

import numpy

The import command tells Python to import the numpy library. We can then use an object from the NumPy library by appending numpy. to the name of the object. To demonstrate this run the following command in the console.

numpy.sqrt(4)

Here we have used the sqrt() function from the NumPy library to calculate the square root of 4. Since we will be using lots of NumPy functions we can define a shorthand for the name of the library. To show this run the following command in the console.

import numpy as np

Here we have defined the shorthand name np which was can use instead of numpy when using an object. To show this run the following command in the console.

np.exp(1)

Here we have used the exp() function to calculate the value of \(e^1\). If you will only be using a few objects from a library you can import only the ones you will be using. To show this run the following commands in the console.

from numpy import cos

cos(0)

Here we import the cos() function from NumPy and then used it to calculate the value of \(\cos(0)\). Note that we did not need to append the name of the library to the function name.

Note

It is possible to import all objects from a library using the following syntax.

from numpy import *

This is generally discouraged as it can cause naming collisions (e.g., if you had a variable name declared which is the same as an object of a library) and can be inefficient especially if the library contains a large number of objects.