How to create a NumPy 1D-array with equally spaced numbers in an interval?
At times, we need to make arrays of different types like in AP(equally spaced series of numbers), GP(exponentially spaced series of numbers) or HP(reciprocally spaced series of numbers) to solve various problems, especially while solving some scientific or astronomical problem, in order to reduce the calculations. Python is one of the best languages when it comes to the pre-implemented codes, and is present there almost every time, at the cost of processing speed.
Syntax: arange([start,] stop[, step,][, dtype])
- start: This is a default parameter. The value of the first number of the element, the default value of this parameter is 0.
- stop: This is not a default parameter. This has to be greater than the maximum possible value of the last element. e.g. , If you want the last element to be 8, you should give the stop value as 9 or more, depending upon the difference you want between two consecutive numbers in the array.
- step: This is also a default parameter. This number will be the difference between the two consecutive elements in the array. The default value of step is 1.
- dtype: This is also a default parameter. This is the data type of the numbers in NumPy, for simplicity, it is a number(in power of 2) preceded by np.int, e.g., np.int8, np.int16, np.int32.
The function will return an array as per the demand of the user. Let’s see some examples of it:
Example 1: To create a simple array starting from 0 to a given number
[0 1 2 3 4 5 6 7]
Example 2: To create a simple array starting from a given number to another number
[1 2 3 4 5]
Example 3: To create an array from a given number to another number with a given interval.
[ 2 4 6 8 10]
Example 4: We use dtype especially in the cases when we want to deal with images or some other sort of computation.
[ 5 15 25 35 45 55 65 75 85 95]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course