NumPy - linspace() Function
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:
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 :
- In this example, np.linspace(0, 1, num=10) generates an array of 10 numbers between 0 and 1, including both endpoints.
Table of Content
Syntax of linspace()
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
Parameters:
- start: [optional] start of interval range. By default start = 0
- stop: end of interval range
- num: [int, optional] No. of samples to generate
- retstep: If True, Stop is the last sample By default restep = False
- endpoint: If True, stop is included as the last value. If False, stop is excluded. By default endpoint=True.
- dtype: type of output array
- axis: If start and stop are arrays, axis specifies on what axis will the values be added. If axis = 0, value is added to front, if axis = -1 value is added at the end.
Return Type:
- ndarray
- step : [float, optional], if restep = True
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
.
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.
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)
Output
Step Size: 2.5
Multi-Dimensional Arrays
We can also generate multi-dimensional arrays using linspace(). We can create a 2D array of numbers between 0 and 1:
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....