The numpy.linspace() function is used to generate an array of evenly spaced values between two specified numbers. Instead of defining a step size, the total number of required values is specified and NumPy automatically calculates the spacing between them.
import numpy as np
a = np.linspace(0, 1, num=10)
print(a)
Output
[0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556 0.66666667 0.77777778 0.88888889 1. ]
Explanation:
- 0 is the starting value of the sequence.
- 1 is the ending value, and it is included in the output.
- num=10 specifies that exactly 10 values should be generated.
Syntax
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
Parameters:
- start: Starting value (default 0)
- stop: Ending value of the range
- num: Number of values to generate (default 50)
- endpoint: Includes stop if True (default True)
- retstep: Returns step size if True (default False)
- dtype: Output array data type
- axis: Axis for generation when inputs are array-like (default 0)
Return Type: ndarray (returns step size as well when retstep=True)
Including or Excluding the Stop Value
By default, numpy.linspace() includes the stop value as the last element of the array. This behavior can be changed using the endpoint parameter. Setting "endpoint=False" excludes the stop value and generates evenly spaced values before it.
import numpy as np
b = np.linspace(0, 1, num=10, endpoint=False)
print(b)
Output
[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
Explanation:
- np.linspace(0, 1, num=10) generates values between 0 and 1.
- endpoint=False excludes the value 1 from the output.
Getting the Step Size
The retstep parameter allows linspace() to return the step size along with the generated array. This is useful when the exact spacing between values is required for further calculations.
import numpy as np
array, c = np.linspace(0, 10, num=5, retstep=True)
print("Step Size:", c)
Output
Step Size: 2.5
Explanation:
- num=5 specifies that five evenly spaced values should be generated.
- retstep=True returns the step size between consecutive values.
- The calculated step size is 2.5, which is the difference between adjacent elements.
Multi-Dimensional Arrays
numpy.linspace() can also be used to generate values for multi-dimensional arrays. This is typically done by generating a 1D array and reshaping it into the desired dimensions.
import numpy as np
d = np.linspace(0, 1, num=16).reshape(4, 4)
print(d)
Output
[[0. 0.06666667 0.13333333 0.2 ] [0.26666667 0.33333333 0.4 0.46666667] [0.53333333 0.6 0.66666667 0.73333333] [0.8 0.86666667 0.93333333 1. ]]
Explanation:
- np.linspace(0, 1, num=25) generates 25 evenly spaced values between 0 and 1.
- .reshape(5, 5) converts the 1D array into a 2D array with 5 rows and 5 columns.