5.2.5. Creating linearly spaced arrays#
It is very common to generate one-dimensional arrays of equally spaced values, such as [0, 1, 2, 3, 4] or [0, 0.1, 0.2, 0.3]. We can do it using:
import numpy as np
np.array(range(5))
array([0, 1, 2, 3, 4])
which creates a range from 0 (inclusive) to 5 (exclusive), then converts this range to an array. NumPy provides a shortcut for this: np.arange
np.arange(5)
array([0, 1, 2, 3, 4])
This function takes the same arguments as Python’s range function.
Good practice: np.arange
While range only accepts 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 guarantee the length of the resulting array. Without delving 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 floats 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 as arguments. For example, to create an array that goes from 5.0 (inclusive) to 10.0 (inclusive) 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, 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])