numpy.linspace(start,stop,num=50,endpoint=True,retstep=False,dtype=None,axis=0)
Return evenly spaced numbers over the specified num (evenly spaced intervals )
start | number, Start value of the sequence |
stop | number, Stop value of the sequence |
num | integer ( optional ) default = 50 , number of equal interval samples. |
dtype | data type of output, Optional |
endpoint | Boolean, default is True, To use stop value as last element or not |
retstep | Boolean, default is False, if True it returns the STEP value used along with the samples. |
axis | int, Optional , To use start and stop arrays to create axis of output. |
import numpy as np
print(np.linspace(2,10))
Default value of num ( number of samples ) is 50. We have specified here start=2 and stop=10 so we are getting 50 samples of evenly spaced numbers.
[ 2. 2.16326531 2.32653061 2.48979592 2.65306122 2.81632653
2.97959184 3.14285714 3.30612245 3.46938776 3.63265306 3.79591837
3.95918367 4.12244898 4.28571429 4.44897959 4.6122449 4.7755102
4.93877551 5.10204082 5.26530612 5.42857143 5.59183673 5.75510204
5.91836735 6.08163265 6.24489796 6.40816327 6.57142857 6.73469388
6.89795918 7.06122449 7.2244898 7.3877551 7.55102041 7.71428571
7.87755102 8.04081633 8.20408163 8.36734694 8.53061224 8.69387755
8.85714286 9.02040816 9.18367347 9.34693878 9.51020408 9.67346939
9.83673469 10. ]
Let us specify num ( num = 5 )
print(np.linspace(2,10,5)) # [ 2. 4. 6. 8. 10.]
In above code, start=2, stop=10 and num=5. We are getting 5 elements starting from 2 and ending at 10 with an equal increment of 2.
print(np.linspace(2,10,5,endpoint=False)) # [2. 3.6 5.2 6.8 8.4]
Now the stop value 10 is not included in our output. Now the increment is adjusted to 1.6 to return 5 equal incremental elements in our output.
print(np.linspace(2,10,5,retstep=True))
y=np.linspace(2,10,5,retstep=True)
print(y[1])
Output
(array([ 2., 4., 6., 8., 10.]), 2.0)
2.0
print(np.linspace(2,10,5,dtype=np.int8)) # [ 2 4 6 8 10]
print(np.linspace(2,10,5,dtype=np.int32)) # [ 2 4 6 8 10]
print(np.linspace(2,10,5,dtype=np.float)) # [ 2. 4. 6. 8. 10.]
print(np.linspace([2,5],[6,25],5,axis=0))
Output
[[ 2. 5.]
[ 3. 10.]
[ 4. 15.]
[ 5. 20.]
[ 6. 25.]]
Let us change the axis.
print(np.linspace([2,5],[6,25],5,axis=1))
Output
[[ 2. 3. 4. 5. 6.]
[ 5. 10. 15. 20. 25.]]
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.