Create a Numpy array of evenly spaced samples over a range using numpy.linspace()
Numpy evenly spaced values: In this article we will discus about how to create a Numpy array of evenly spaced samples over a range using numpy.linspace()
.
Numpy.linspace()
np.linspace(): Numpy module provides a function numpy.linspace()
to create a evenly spaced samples over a specified interval i.e.
Syntax: numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
Where,
- start : Represents the start value of the range
- stop : Represents the end value of the range (Actually array doesn’t include this value but it acts as an end point)
- num : Represents the number of samples to be generated (If it is not provided then optional value is taken as 50)
- dtype : Represents datatype of elements.
To use Numpy we have to include the below module i.e.
import numpy as np
Let’s see below two examples to understand the concept.
Example-1 : Create 5 evenly spaced samples in interval [10, 50]
import numpy as np # Create 5 evenly spaced samples in interval [10, 50] temp_arr = np.linspace(10,50,5) print(temp_arr)
Output : [10. 20. 30. 40. 50.]
We can also specify the datatype as int32 by type.
import numpy as np # Create 5 evenly spaced samples in interval [10, 50] temp_arr = np.linspace(10,50,5,dtype=np.int32) print(temp_arr)
Output : [10 20 30 40 50]
- Python NumPy logspace() Function
- Python Programming – NumPy
- numpy.arange() : Create a Numpy Array of evenly spaced numbers in Python
Example-2 : Get the Step size from numpy.linspace()
Python linespace: When we will pass retstep=True
in numpy.linspace().
Then it will return step size between samples.
import numpy as np # Create 5 evenly spaced samples in interval [10, 50] temp_arr, step = np.linspace(10,50,5,dtype=np.int32,retstep=True) print('Printing the Numpy Array contents: ') print(temp_arr) print('The step size between two samples : ', step)
Output : Contents of the Numpy Array : [10 20 30 40 50] Step size between two elements : 10.0