NumPy linspace() Function (original) (raw)

Last Updated : 24 Jan, 2025

**linspace() function in NumPy returns an array of evenly spaced numbers over a specified range. Unlike the range() function in Python that generates numbers with a specific step size. linspace() allows you to specify the total number of points you want in the array, and NumPy will calculate the spacing between the numbers automatically.

Let's understand with the help of an example:

Python `

import numpy as np

Generate 10 numbers between 0 and 1

array = np.linspace(0, 1, num=10) print(array)

`

Output

[0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556 0.66666667 0.77777778 0.88888889 1. ]

**Explanation :

Table of Content

Syntax of linspace()

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

**Parameters:

**Return Type:

Including or Excluding the Stop Value

By default, linspace() includes the stop value. However, you can exclude it by setting the endpoint parameter to False.

Python `

import numpy as np

Generate 10 numbers between 0 and 1

array_without_endpoint = np.linspace(0, 1, num=10, endpoint=False)

print(array_without_endpoint)

`

Output

[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]

Getting the Step Size

retstep parameter allows you to return the step size between each number along with the array.

Python `

import numpy as np

Generate 5 numbers between 0 and 10 and return the step size

array, step = np.linspace(0, 10, num=5, retstep=True)

print("Step Size:", step)

`

Multi-Dimensional Arrays

We can also generate multi-dimensional arrays using linspace(). We can create a 2D array of numbers between 0 and 1:

Python `

import numpy as np

Create a 2D array of 5x5 numbers between 0 and 1

array_2d = np.linspace(0, 1, num=25).reshape(5, 5)

print(array_2d)

`

Output

[[0. 0.04166667 0.08333333 0.125 0.16666667] [0.20833333 0.25 0.29166667 0.33333333 0.375 ] [0.41666667 0.45833333 0.5 0.54166667 0.58333333] [0.625 0.66666667 0....