The linspace() method creates an array with evenly spaced elements over an interval.
linspace() Syntax
The syntax of linspace() is:
numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None, axis = 0)
linspace() Argument
The linspace() method takes the following arguments:
start- the start value of the sequence, 0 by default (can bearray_like)stop- the end value of the sequence (can bearray_like)num(optional)- number of samples to generate (int)endpoint(optional)- specifies whether to include end value (bool)retstep(optional)- ifTrue, returns steps between the samples (bool)dtype(optional)- type of output arrayaxis(optional)- axis in the result to store the samples(int)
Notes:
stepcan't be zero. Otherwise, you'll get aZeroDivisionError.- If
dtypeis omitted,linspace()will determine the type of the array elements from the types of other parameters. - In
linspace(), thestopvalue is inclusive.
linspace() Return Value
The linspace() method returns an array of evenly spaced values.
Note: If retstep is True, it also returns the stepsize i.e. interval between two elements.
Example 1: Create a 1-D Array Using linspace
Output
Array1: [2. 2.25 2.5 2.75 3. ] Array2: [2. 2.2 2.4 2.6 2.8] Array3: [2. 2.25 2.5 2.75 3. ] Step Size: 0.25
Example 2: Create an n-D Array Using linspace
Output
Array1: [[1. 2. ] [1.5 2.5] [2. 3. ] [2.5 3.5] [3. 4. ]] Array2: [[1. 1.5 2. 2.5 3. ] [2. 2.5 3. 3.5 4. ]]
Key Differences Between arange and linspace
Both np.arange() and np.linspace() are NumPy functions used to generate numerical sequences, but they have some differences in their behavior.
arange()generates a sequence of values fromstarttostopwith a givenstepsize whereaslinspacegenerates a sequence ofnumevenly spaced values fromstarttostop.arange()excludesstopvalue whereaslinspaceincludesstopvalue unless specified otherwise byendpoint = False
Let us see an example.
Output
Using arange: [10 14 18 22 26 30 34 38 42 46] Using linspace: [10. 23.33333333 36.66666667 50. ]