Array based on a numerical range

The arange function of NumPy functionally resembles Python's range function. Based on a start value, stop value, and step value to increment or decrement subsequent values, the arange function generates a set of numbers. Just like the range function, the start and step arguments are optional here. But unlike range, which generates a list, arange generates an array:

# Creating an array with continuous values from 0 to 5
In [44]: np.arange(6)
Out [44]: array([0, 1, 2, 3, 4, 5])

# Creating an array with numbers from 2 to 12 spaced out at intervals of 3
In [45]: np.arange(2, 13, 3)
Out [45]: array([ 2, 5, 8, 11])

The linspace function generates an array of linearly spaced samples for a given start point and end point. Unlike the arrange function, which specifies the incremental/decremental interval, the linspace function accepts the number of samples to be generated as an optional argument. By default, 50 samples are generated for a given start point and end point:

# Creating a linearly spaced array of 20 samples between 5 and 10
In [47]: np.linspace(start = 5, stop = 10, num = 20)
Out [47]:
array([ 5. , 5.26315789, 5.52631579, 5.78947368, 6.05263158,
6.31578947, 6.57894737, 6.84210526, 7.10526316, 7.36842105,
7.63157895, 7.89473684, 8.15789474, 8.42105263, 8.68421053,
8.94736842, 9.21052632, 9.47368421, 9.73684211, 10. ])

Similarly, the logspace and geomspace functions create an array of numbers following logarithmic and geometric sequences to be created.

The arange function and linspace function do not allow for any shape specification by themselves and produce 1D arrays with the given sequence of numbers. We can very well use some shape manipulation methods to mold these arrays to the desired shape. These methods will be discussed in the last part of this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset