NumPy linspace()

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 be array_like)
  • stop- the end value of the sequence (can be array_like)
  • num(optional)- number of samples to generate (int)
  • endpoint(optional)- specifies whether to include end value (bool)
  • retstep(optional)- if True, returns steps between the samples (bool)
  • dtype(optional)- type of output array
  • axis(optional)- axis in the result to store the samples(int)

Notes:

  • step can't be zero. Otherwise, you'll get a ZeroDivisionError.
  • If dtype is omitted, linspace() will determine the type of the array elements from the types of other parameters.
  • In linspace(), the stop value 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 from start to stop with a given step size whereas linspace generates a sequence of num evenly spaced values from start to stop.
  • arange() excludes stop value whereas linspace includes stop value unless specified otherwise by endpoint = 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.        ]