
How to make an arithmetic progression in NumPy (Python)
The NumPy arange()
is almost the same as the Python range. The arange()
returns an arithmetic progression.
import numpy
a1 = numpy.arange(3)
a2 = numpy.arange(7)
a3 = numpy.arange(2, 5)
print(a1) # [0 1 2]
print(a2) # [0 1 2 3 4 5 6]
print(a3) # [2 3 4]
If there is one argument, it simply returns the integers from 0 to n-1. If the function has two arguments (m, n), it returns from m to n-1.
Step
Here are arithmetic progressions with step three:
import numpy
a1 = numpy.arange(2, 20, 3)
a2 = numpy.arange(2, 21, 3)
a3 = numpy.arange(2, 22, 3)
a4 = numpy.arange(2, 23, 3)
a5 = numpy.arange(2, 24, 3)
print(a1) # [ 2 5 8 11 14 17]
print(a2) # [ 2 5 8 11 14 17 20]
print(a3) # [ 2 5 8 11 14 17 20]
print(a4) # [ 2 5 8 11 14 17 20]
print(a5) # [ 2 5 8 11 14 17 20 23]
The third argument is the step of progression. The second argument is the max of progression, not the last value of progression.
Arange of decimal step
import numpy
a = numpy.arange(3, 7, 0.1)
print(a)
# [3. 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 4. 4.1 4.2 4.3 4.4 4.5 4.6 4.7
# 4.8 4.9 5. 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 6. 6.1 6.2 6.3 6.4 6.5
# 6.6 6.7 6.8 6.9]
Let's draw the curve by that technique.
import numpy
from matplotlib import pyplot
x = numpy.arange(-5, 20, 0.1)
y = numpy.array([a * a for a in x])
pyplot.plot(x, y)
pyplot.savefig('plot.jpg')

arange() and linspace()
import numpy
a = numpy.arange(1, 3, 0.1)
b = numpy.linspace(1, 3, 21)
print(a)
# [1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2. 2.1 2.2 2.3 2.4 2.5 2.6 2.7
# 2.8 2.9]
print(b)
# [1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2. 2.1 2.2 2.3 2.4 2.5 2.6 2.7
# 2.8 2.9 3. ]
arange()
and linspace()
are similar. linspace()
takes the start, stop, and number of samples. In the above exmample, the function generates 21 values and those contain the start and stop value (1 and 3).
Comments
Powered by Markdown