The numpy module is every Python programmer's go-to module when creating numerical applications. The module is typically used with arrays, and depending on the application, you may need to create arrays with evenly-spaced values.
The np.linspace() method can help you accomplish exactly this. Though the method may seem simplistic, it has several uses and is often essential to any developer's numerical programming toolkit.
In this brief guide, we discuss how you can use the np.linspace() method to create arrays with evenly-spaced values.
How to Use np.linspace() to Create Evenly-Spaced Arrays
Python is vast and offers several techniques to create a range of evenly-spaced numbers. The np.linspace() method is one of the many approaches to the problem.
The method expects the start and stop parameters and doesn't function without them. As you can guess, these parameters allow you to set the beginning and the end of a range.
Let's see the method in action:
>>> import numpy as np >>> np.linspace(1, 5) array([1. , 1.08163265, 1.16326531, 1.24489796, 1.32653061, 1.40816327, 1.48979592, 1.57142857, 1.65306122, 1.73469388, 1.81632653, 1.89795918, 1.97959184, 2.06122449, 2.14285714, 2.2244898 , 2.30612245, 2.3877551 , 2.46938776, 2.55102041, 2.63265306, 2.71428571, 2.79591837, 2.87755102, 2.95918367, 3.04081633, 3.12244898, 3.20408163, 3.28571429, 3.36734694, 3.44897959, 3.53061224, 3.6122449 , 3.69387755, 3.7755102 , 3.85714286, 3.93877551, 4.02040816, 4.10204082, 4.18367347, 4.26530612, 4.34693878, 4.42857143, 4.51020408, 4.59183673, 4.67346939, 4.75510204, 4.83673469, 4.91836735, 5. ])
As you can see, the output is an ndarray having equally spaced intervals between the first and last values. This ndarray is called the linear space or "linspace."
The np.linspace() method is typically used with int or float values, which are scalar values. However, you can also pass any non-scalar array-like object to the method. There is no default value for the start and stop parameters – remember that the method expects you to pass these values every time.
Note that our method returns a closed range since the "5" value is the final value in the array. This is uncommon behavior among Python methods since most methods tend to avoid including the end-of-range value.
This characteristic of the np.linspace() method might seem like an oversight, but it's one of the most helpful aspects of the method.
The method accepts a third parameter, which is the optional parameter num. This parameter allows you to set the number of values or "points" in the array.
For instance, if we run the same method as before but with the num parameter set to 10, we will see the following:
>>> import numpy as np >>> np.linspace(1, 5, num=10) array([1. , 1.44444444, 1.88888889, 2.33333333, 2.77777778, 3.22222222, 3.66666667, 4.11111111, 4.55555556, 5. ])>
So, the output array has ten equally-spaced values between one and five. If you don't pass this parameter, the method will use the default value of num, which is 50. This is what happened in the previous example.
Bear in mind that you can also use named parameters if you prefer. Here's what this would look like:
>>> import numpy as np >>> np.linspace(start=1, stop=5, num=10) array([1. , 1.44444444, 1.88888889, 2.33333333, 2.77777778, 3.22222222, 3.66666667, 4.11111111, 4.55555556, 5. ])>
Using named parameters is a great idea if you want to ensure your code is as readable as possible. However, most applications that use np.linspace() use it without named parameters.
Here's another way you could use the np.linspace() method:
>>> import numpy as np >>> np.linspace(1, 5, num=10) array([-5. , -4.58333333, -4.16666667, -3.75 , -3.33333333, -2.91666667, -2.5 , -2.08333333, -1.66666667, -1.25 , -0.83333333, -0.41666667, 0. , 0.41666667, 0.83333333, 1.25 , 1.66666667, 2.08333333, 2.5 , 2.91666667, 3.33333333, 3.75 , 4.16666667, 4.58333333, 5. ])
As you might be able to tell, the num parameter acts as a positional argument in the program above. With it, we're creating a linear space with 25 values between -5 and 5.
The num parameter correlates to the resolution or sampling of the array. If you set the parameter to 100, you will have an array with a sample size of 100. If you set it to 10, you will have an array with a resolution of 10.
The interesting thing about the np.linspace() method is that you can also define the range with non-integer numbers. Let's see it in action:
>>> import numpy as np >>> np.linspace(-3.4, 1.7, 20) array([-3.4 , -3.13157895, -2.86315789, -2.59473684, -2.32631579, -2.05789474, -1.78947368, -1.52105263, -1.25263158, -0.98421053, -0.71578947, -0.44736842, -0.17894737, 0.08947368, 0.35789474, 0.62631579, 0.89473684, 1.16315789, 1.43157895, 1.7 ])
The array above comprises 20 equally spaced numbers that begin and end at the same values we supplied in the start and stop parameters.
In this section, we've discussed the workings of the three main parameters of the np.linspace() method.
There are a handful of other optional input parameters that you can use with the method to modify the output array further. We'll discuss these parameters next.
Other Useful np.linspace() Parameters
Parameter | Description | Default value |
axis | The axis parameter sets the axis along which the method's results are stored. You can only use this parameter when you pass non-scalar start and stop values. So, you must pass array values in the start and stop parameters to use this parameter. | - |
dtype | It sets the data type of the output array. | - |
endpoint | To exclude the endpoint from the output array, you can set the endpoint parameter to False. When you do this, the method will treat the interval as half-open. | True |
retstep | Setting retstep to True results in the function returning the array and a float value with the step size between each element. When not used, the method only returns the array. | False |
To read the full details of the np.linspace() method and its parameters, visit the official Python documentation.
Here's an example of using all the parameters of the np.linspace() method:
linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0 )
The result of running the method will be:
- An ndarray with the vector space.
- If retstep is set to True, the step size is float.
Now that you know all the basics of using the np.linspace() method, let's look at a real-world example of using it.
Real-World Example of Using np.linspace()
Suppose a company produces packaged food in its food production factory. The factory has a conveyor belt system, and a numeric value references the position along the belt. This value represents the length of the conveyor belt from its starting point.
Now, let's say there are 27 temperature sensors installed at equal lengths along one of the critical stretches of this conveyor belt. The first of these sensors is at position 17.5 along the belt. The final sensor is at position 46.2.
Each sensor outputs data that can be read as a Python list. Let's assume a few readings of these sensors in Celsius and put them in an array like so:
temps = [17.6, 18.9, 18.0, 18.9, 16.7, 14.3, 13.7, 13.8, 13.6, 15.7, 18.6, 17.5, 18.4, 18.0, 17.2, 16.9, 16.8, 17.0, 15.9, 17.2, 17.7, 16.9, 17.2, 17.8, 17.5, 16.9, 17.2]
The factory's manager needs to monitor these temperatures, and the best way to do this is to plot the readings' positions with the sensors' positions.
This is to ensure that the temperature of the conveyor belt remains within the tolerance at each point of this stretch of the belt.
To plot the temperature values as required, you will need to use matplotlib like so:
import matplotlib.pyplot as plt temps = [17.6, 18.9, 18.0, 18.9, 16.7, 14.3, 13.7, 13.8, 13.6, 15.7, 18.6, 17.5, 18.4, 18.0, 17.2, 16.9, 16.8, 17.0, 15.9, 17.2, 17.7, 16.9, 17.2, 17.8, 17.5, 16.9, 17.2] plt.plot(temps) plt.title("Temperatures along critical stretch (ºC)") plt.ylabel("Temperature (ºC)") plt.xlabel("List index") plt.show()
With this code, we are plotting the values in temps and setting the title and axis labels. The output of the plot will be an X-Y graph indicating the temperatures along the stretch with respect to the index of the sensor.
However, the manager won't find this graph helpful since they want to know the temperature of the belt at standard reference positions.
Therefore, we must create a temperature index that matches the reference positions of the belt. It should be clear now how np.linspace() can help us here.
We are dealing with three values: the start value of 17.5, the stop value of 46.2, and the fact that there are 27 sensors along the belt.
Here's how we can use the np.linspace() method to help the manager see the readings:
>>> import numpy as np >>> position = np.linspace(17.5, 46.2, 27) >>> position array([17.5 , 18.60384615, 19.70769231, 20.81153846, 21.91538462, 23.01923077, 24.12307692, 25.22692308, 26.33076923, 27.43461538, 28.53846154, 29.64230769, 30.74615385, 31.85 , 32.95384615, 34.05769231, 35.16153846, 36.26538462, 37.36923077, 38.47307692, 39.57692308, 40.68076923, 41.78461538, 42.88846154, 43.99230769, 45.09615385, 46.2 ])
As you can see, "position" is the linear space and shows the correct locations of the sensors along the belt. With this data, you can plot the temperature data against this "position" array. Here's how:
plt.plot(position, temps) plt.title("Temperatures along critical stretch (ºC)") plt.ylabel("Temperature (ºC)") plt.xlabel("Position on conveyor belt") plt.show()
The primary difference between this code and the previous code is that we're using the position array as an argument to plt.plot().
Running this code will return a graph with the x-axis you'd expect, which is the position on the conveyor belt. On the y-axis, you will see the temps at the reference positions.
This is a typical usecase of the np.linspace() method, and with this guide handy, you will have no trouble using it in your programs.