![]() |
VOOZH | about |
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, 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.
NumPy has built-in methods called np.arange()and np.linspace() which are capable of creating an array of a given integer type(in bytes), with equal spacing between the numbers. In this article, we will see how to create an array with evenly spaced values in NumPy.
Below are the ways by which we can see how to create an array with evenly spaced values in NumPy:
In this example, a 1D array named myArray is created using numpy.arange() with a single argument, generating numbers from 0 up to (but not including) 8. The resulting array is then printed.
Output:
[0 1 2 3 4 5 6 7]In this example, the numpy.arange() function generates a 1D array named myThirdArray starting from 2, ending just before 12, with a step size of 2 between consecutive elements. The resulting array is then displayed.
Output:
[ 2 4 6 8 10]We use dtype especially in the cases when we want to deal with images or some other sort of computation.
Output:
[ 5 15 25 35 45 55 65 75 85 95]
In this example, numpy.linspace() creates a 1D array arr with 9 evenly spaced numbers starting from -2 and ending at 2, inclusive. The array is then printed.
Output:
[ 1. 2.28571429 3.57142857 4.85714286 6.14285714 7.42857143 8.71428571 10.]
In this example, numpy.linspace() generates a 1D array arr with 11 evenly spaced numbers from 0 to 10. Additionally, it returns the step size between consecutive numbers, which is then printed alongside the array.
Output:
[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
Step size: 1.0
In this example, numpy.linspace() produces a 1D integer array arr with 11 evenly spaced integers from 0 to 10, inclusive. The resulting integer array is then printed.
Output:
[ 0 1 2 3 4 5 6 7 8 9 10]