Python – numpy.linspace()

Filed Under: NumPy
Numpy Linspace

Being a sequence generator, the numpy.linspace() function is used to generate a sequence of numbers in linear space with a uniform step size.

Numpy generally can generate sequences using numpy.arange(), but when we use floating-point arguments, it can result in a loss of precision, which may cause an unpredictable output.

To avoid any potential loss of precision due to the floating-point precision, numpy provides us with a separate sequence generator in numpy.linspace(), which is the preferred option if you already know the number of elements you need. But you generally get the same output using both linspace() and arange() with appropriate parameters, so both can be chosen for the same task.

For example, the following code plots 2 linear sequences between 0 and 10 using numpy.linspace() to show that there is uniformity generated by the sequence.

import numpy as np
import matplotlib.pyplot as plt

y = np.zeros(5)
x1 = np.linspace(0, 10, 5)
x2 = np.linspace(0, 10, 5)
plt.plot(x1, y, 'o')
plt.plot(x2, y + 0.5, 'o')
plt.ylim([-0.5, 1])
plt.show()

Output:

Np Linspace Plot
Np Linspace Plot

Syntax

Format: array = numpy.linspace(start, end, num=num_points) will generate a uniform sequence between start and end, with num_points of total elements.

Here,

  • start -> Starting point (included) of the range
  • end -> Endpoint (included) of the range
  • num -> Total number of points in the sequence

Let’s understand this using a couple of examples:

import numpy as np

a = np.linspace(0.02, 2, 10)

print('Linear Sequence from 0.02 to 2:', a)
print('Length:', len(a))

Output

Linear Sequence from 0.02 to 2: [0.02 0.24 0.46 0.68 0.9  1.12 1.34 1.56 1.78 2.  ]
Length: 10

The above snippet generates a uniform sequence between 0.02 to 2, having 10 elements in it.

The endpoint keyword argument

If you don’t want to include the last point in the sequence calculations, there is another keyword argument endpoint, which can be set to False. ( It is True by default )

import numpy as np

a = np.linspace(0.02, 2, 10, endpoint=False)

print('Linear Sequence from 0.02 to 2:', a)
print('Length:', len(a))

Output

Linear Sequence from 0.02 to 2: [0.02  0.218 0.416 0.614 0.812 1.01  1.208 1.406 1.604 1.802]
Length: 10

As you can observe, the last point (2) has not been included in the sequence, so the step size is also different, which will generate a totally different sequence now.

The retstep keyword argument

This is a boolean optional argument, if specified, also returns the step size along with the sequence array, resulting in a tuple as the output

import numpy as np

a = np.linspace(0.02, 2, 10, retstep=True)

print('Linear Sequence from 0.02 to 2:', a)
print('Length:', len(a))

Output

Linear Sequence from 0.02 to 2: (array([0.02, 0.24, 0.46, 0.68, 0.9 , 1.12, 1.34, 1.56, 1.78, 2.  ]), 0.22)
Length: 2

Since the output is a tuple, it’s length is 2, and not 10!

The axis keyword argument

This sets the axis in the result to store the samples. It is used only if the start and endpoints are of the array datatype.

By default (axis=0), the samples will be along a new axis inserted at the beginning. We can use axis=-1 to get an axis at the end.

import numpy as np

p = np.array([[1, 2], [3, 4]])
q = np.array([[5, 6], [7, 8]])

r = np.linspace(p, q, 3, axis=0)
print(r)
s = np.linspace(p, q, 3, axis=1)
print(s)

Output

array([[[1., 2.],
        [3., 4.]],

       [[3., 4.],
        [5., 6.]],

       [[5., 6.],
        [7., 8.]]])

array([[[1., 2.],
        [3., 4.],
        [5., 6.]],

       [[3., 4.],
        [5., 6.],
        [7., 8.]]])

In the first case, since axis = 0, we take sequence limits from the first axis.

Here, the limits are the subarray pairs [1, 2] and [5,6], as well as [3, 4] and [7,8], taking elements from the first axis of p and q. Now we compare corresponding elements from the resulting pair to generate the sequences.

So the sequences are [[1 to 5], [2 to 6]] for the first row and [[3 to 7], [4 to 8]], for the second pair(row) which is evaluated and combined to form [ [[1, 2], [3, 4]], [[3, 4], [5, 6]], [[5, 6], [7,8]] ],

The second case will insert new elements in axis=1, or the columns. So the new axis will have been generated via the column sequences. instead of the row sequences.

The sequences [1, 2] to [5, 7] and [3, 4] to [7, 8] are considered and inserted into the columns of the result, resulting in [[[1, 2], [3, 4], [5, 6]], [[3, 4], [5, 6], [7, 8]]].


References


Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages