In Numpy, we can create array from numerical ranges by using the following NumPy functions.
This function returns an ndarray. It creates an ndarray object containing evenly spaced values within a given range of interval.
numpy.arange(start, stop, step, dtype)
- start: The starting of an array. If it is omitted then it defaults to 0.
- stop: This is the ending of an array. This value is excluded.
- step: It is used for spacing between values default is 1.
- dtype: It is used to describe the data type of the numpy array items.
import numpy as np a= np.arange(1,9,2,float) print(a)
[1. 3. 5. 7.]
Similar as arrange() function. In this function, only returns evenly separated values over a specified interval instead of step size.
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
- start: It is used to represent starting values of sequence.
- stop: It is used to represents the stopping value of the sequence.
- num: It represents the amount of evenly spaced samples over the interval to be generated. Its default is 50.
- endpoint: If the stop value is included it is true else false, if not included.
- retstep: It return samples and step between the consecutive numbers, if it is true.
- dtype: It is used to represent the data type of ndarray.
import numpy as np a=np.linspace(10,100,10,endpoint=True) b=np.linspace(10,100,10, retstep=True) print(a) print(b)
[ 10. 20. 30. 40. 50. 60. 70. 80. 90. 100.] (array([ 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.]), 10.0)
This function returns an ndarray, which creates an array by using the numbers that are evenly separated on a log scale.
numpy.logspace(start, stop, num, endpoint, base, dtype)
- start: It is used to represents the starting value of sequence in the base.
- stop: It is used to represents the stopping value of sequence in the base
- num: It is used to give the number of values between the range.Its default is 50.
- endpoint: If it is True then stop is the last value in the range.
- base: It represent the base of log space, Its default is 10.
- dtype: It represents the data type of the ndarray elements.
import numpy as np a=np.logspace(1,5,num=5, base=2) print(a)
Output: [ 2. 4. 8. 16. 32.]