The numpy.linspace function is used to create a set of evenly spaced numbers within a defined interval.
Syntax
numpy.linspace(start, stop, num = 50, endpoint = True/False, retstep = False/True, dtype = None)
Parameters
The function can accept the following parameters −
start − Start of the sequence; by default, it is considered as zero.
stop − Endpoint of the sequence.
num − Number of elements to be generated between start and stop.
endpoint − It controls whether the stop value is included in the output array or not. If the endpoint is True, then the stop parameter is included as the the last item in the nd.array. If endpoint is False, then the stop parameter is not included.
retstep − If retstep=true, then it returns samples and step. By default, it is False.
dtype − It describes the type of output array.
Example 1
Let us consider the following example −
# Import numpy library import numpy as np # linspace() function x = np.linspace(start = 1, stop = 20, num = 10) # round off the result y = np.round(x) print ("linspace of X :\n", y)
Output
It will generate the following output −
linspace of X : [ 1. 3. 5. 7. 9. 12. 14. 16. 18. 20.]
Example 2
np.arange works somewhat in the same way as np.linspace, but there is a slight difference.
np.linspace uses a count that decides how many values you are going to get in between the min and max values of the range.
np.arange uses a step value to get a set of evenly spaced values in a range.
The following example highlights the difference between these two methods.
# Import the required library import numpy as np # np.arange A = np.arange(0, 20, 2) print ("Elements of A :\n", A) # np.linspace B = np.linspace(0, 20, 10) B = np.round(B) print ("Elements of B :\n", B)
Output
It will generate the following output −
Elements of A : [ 0 2 4 6 8 10 12 14 16 18] Elements of B : [ 0. 2. 4. 7. 9. 11. 13. 16. 18. 20.]