NumPy linspace() function
In this tutorial, we will cover
numpy.linspace() function of the Numpy library.
This function is used to return evenly spaced numbers over a specified interval.
This function is similar to Numpy arange() function with the only difference being, instead of step size, the number of evenly spaced values between the interval is specified using the
With the help of this function, the step size is calculated implicitly.
In this function, the endpoint of the interval can optionally be excluded.
In the newest versions of NumPy, the non-scalar values of start and stop parameters(used to define the interval) are supported by this function.
The required syntax to use this function is as follows:
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
The parameters of the above-mentioned function are as follows:
This parameter is used to represents the starting value of the interval.
This parameter is used to represents the stopping value of the interval.
This parameter indicates the amount of evenly spaced samples over the interval to be generated. The default value of this parameter is 50.
This parameter's true value is used to indicate that the stopping value is included in the interval.
The value of this parameter is a boolean value and it is used to represent the steps and samples between the consecutive numbers.
This parameter is used to represent the data type of the array items.
This function will return the array within the range specified.
This function will return the value of step in the case if
retstep parameter is True which usually indicates the size of the spacing between the samples.
Now it's time to take a look at the examples using this function.
Below we have the code snippet explaining how to use this function:
import numpy as np a = np.linspace(20, 40, 8, endpoint = True) print("The array over the given range is ") print(a)
The array over the given range is
[20. 22.85714286 25.71428571 28.57142857 31.42857143 34.28571429
37.14285714 40. ]
Below we have the code snippet for the graphical illustration of this function, using Matplotlib library:
import matplotlib.pyplot as plt N = 10 y = np.zeros(N) x1 = np.linspace(0, 20, N, endpoint=True) x2 = np.linspace(0, 20, N, endpoint=False) plt.plot(x1, y, '*') plt.plot(x2, y + 0.8, 'o') plt.show()
In this tutorial, we covered the
numpy.linspace() function of the Numpy library. We covered its syntax, parameters as well as the value returned by this function along with multiple code examples.