How to Use Numpy Linspace in Python An interactive walkthrough.


Numpy is a powerful python library that facilitates linear algebra techniques to be used in various discplines such as machine learning, data engineering and data science. It specifically excels in creating vectors, matrices and applying mathematical operations on these components. Many popular python packages such as pandas, scikit learn and scipy rely heavily on numpy.

What is Linspace

Linspace belongs to the category of interval functions. Other numpy functions that fall in this category are:

  • np.zeros
  • np.ones
  • np.arrange

Numpy interval functions are closely related to the mathematical and algebraic concept of intervals. A mathematical interval is a set of points between two numbers, the startpoint and endpoint of the interval.

Linspace is a numpy function that generates an interval with the following charateristics:

  1. start point, beginning number of the interval
  2. end point, end number of the interval
  3. a fixed number of points, generated between the start point and end point.
  4. constant distance between consecutive points. Distance is determined as:

    (end point - start point + 1)/number of points

Visual example

Let's visualize the above characteristics by using a number line where we show the points in the interval that we are including. Suppose you want to generate 4 points between the numbers 1 and 4, including the endpoint. Linspace generates the following range of values:

The timeline shows 4 consecutive sample (1,2,3,4) where the end pont is included (closed circle)

Note that the distance / space between two consecutive points is fixed: 1. This distance is determined by the start point, end point and number of points: (endpoint - start point + 1)/number of points -> (4-1 +1)/4 = 1

Linspace python code to generate the above timeline is as follows:

import numpy as np
output = np.linspace(start = 1, stop = 4, num = 4, endpoint = True, retstep = False)
print (output)
## [1. 2. 3. 4.]

Syntax and Interactive playground

Insert parameters in the following text boxes and click on "Generate"

output :