Creating linearly spaced arrays

5.2.5. Creating linearly spaced arrays#

It is very common to generate unidimensional arrays of equally spaced values, such as [0, 1, 2, 3, 4] or [0, 0.1, 0.2, 0.3]. We could do it using:

import numpy as np

np.array(range(5))
array([0, 1, 2, 3, 4])

which creates a range from 0 (incl.) to 5 (excl.), then converts this range to an array. NumPy provides a shortcut for it: np.arange

np.arange(5)
array([0, 1, 2, 3, 4])

This function takes the same arguments as the Python’s range function.

Good practice: np.arange

While range only takes integers as arguments, np.arange also accepts floats. For example:

np.arange(0, 0.5, 0.1)

generates:

array([0. , 0.1, 0.2, 0.3, 0.4])

However, this practice is not always recommended due to potential floating point issues that cannot guaranty the length of the resulting array. Without going further into these issues, just remind that in most cases, np.arange should be used only with integers. For the example above,

np.arange(5) / 10

is safer and gives the same result:

array([0. , 0.1, 0.2, 0.3, 0.4])

Another function to create equally spaced series of float is np.linspace, which takes as arguments the initial value, the final value, and the number of points in the new array. By default, np.linspace includes both the initial and final values. For example, to create an array that goes from 5.0 (included) to 10.0 (included) and that contains 11 elements:

np.linspace(5.0, 10.0, 11)
array([ 5. ,  5.5,  6. ,  6.5,  7. ,  7.5,  8. ,  8.5,  9. ,  9.5, 10. ])

To exclude the final value, we set the endpoint argument to False.

np.linspace(5.0, 10.0, 10, endpoint=False)
array([5. , 5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5])