In this article we will discuss how to create a Numpy array of evenly spaced samples over a range using numpy.linspace().

Numpy.linspace()

Python’s Numpy module provides a function to create a evenly spaced samples over a specified interval i.e.

Arguments:
start : It’s the start of Sequence / range.
stop : End Value of range, array doesn’t include this value but it’s an end marker
num : Numbers of samples to be generated. It’s optional, if not provided default value will be 50.
dtype : Data type of elements, if not provided will be deduced from other arguments.

It returns num number of evenly spaced samples over the range [start, stop)

To use Numpy in our code we need to include following module i.e.

Checkout some examples,

Example 1:

Create 5 evenly spaced samples in interval [20, 60)

Contents of the Numpy array containing 5 Samples are,

Data type of elements in this Numpy array is float64.

As default type of elements are deduced automatically therefore in this case it was float. We can also specify the datatype by dtype argument i.e.

Contents of the Numpy array containing 5 Samples are,

Data type of elements in this Numpy array is int.

Example 2:

Get the Step size from numpy.linspace()

If we pass the argument retstep=True in numpy.linspace() then it will return step size between samples too along with the Numpy array of samples i.e.

It returns a tuple of step size & Numpy Array i.e.

Complete example is as follows,

Output:

 

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,