numpy.linspace() in Python


The numpy.linspace() function in Python returns evenly spaced numbers over the specified interval. This function is similar to The Numpy arange function but it uses the number instead of the step as an interval.

Basic Syntax

numpy.linspace() in Python function overview
numpy.linspace() in Python function overview

Following is the basic syntax for numpy.linspace() function:

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

And the parameters are:

Parameter Description
start Specify the start of the interval range. The default value is 0.
stop provide end of the interval range.
num [Optional] the number of samples to generate. The default is 50.
endpoint [Optional] if true then stop is the last sample.
retstep [Optional] if the value is true then return the spacing between samples
dtype [Optional] dtype is the type of output array.

Returns

  • Returns ndarray which array of equally spaced samples.
  • If retstep is true then returns float which is the size of the spacing between samples.

Examples

Following are the examples for Numpy linspace() function in Python.

Example 1:

# Python Program for numpy.linspace method 
import numpy as np 

# basic linspace 
print("Array1 = \n", np.linspace(2.0, 3.0, num=5), "\n") 
  
# endpoint is false
arr = np.linspace(2.0, 3.0, num=5, endpoint=False)
print("Array2 = \n", arr) 

The output should be:

Array1 =
array([ 2. , 2.25, 2.5 , 2.75, 3. ])
Array2 =
array([ 2. , 2.2, 2.4, 2.6, 2.8])

Example 2: Graphical Illustration

# Graphical Illustration of numpy.linspace() 
import numpy as np 
import matplotlib.pyplot as pyplt
  
# creating points
N = 8
y = np.zeros(N)

# getting arrays x1 and x2
x1 = np.linspace(0, 10, N, endpoint=True)
x2 = np.linspace(0, 10, N, endpoint=False)

# creating plot
pyplt.plot(x1, y, 'o')
pyplt.plot(x2, y + 0.5, 'o')
pyplt.ylim([-0.5, 1])
pyplt.show() 

The output should be:

numpy.linspace() output
numpy.linspace() output