My Coding > Programming language > Python > Python FAQ > Python: How to make iterations with fractional step

Python: How to make iterations with fractional step

To make iterations with integer step in Python you can use function range, which can take only integer parameters. To make iterations over fractional parameters, it is necessary to use numpy.arange() function or use some trick with range

in this example I will print all numbers from 0 ti 5.0 with step 0.2

Numpy fractional step

This is a bit slower version, because you need to load Numpy library first, and then generate numpy structure with function arange().


import numpy as np
top = 5
step = 0.2
for i in np.arange(0, top, step):
    print(i)

Range with fractional step

range() can only works with integer parameters, so it is necessary to make a conversion, but I do recommend to use this version of iterations.


top = 5
step = 0.2
for i in range(int(top/step)):
    print(i*step)

In range() you need to show how many steps to do: int(top/step), and then, recalculate step to real value i*step

In both cases, output will be identical:


0.0
0.2
0.4
0.6000000000000001
0.8
1.0
1.2000000000000002
1.4000000000000001
1.6
1.8
2.0
2.2
2.4000000000000004
2.6
2.8000000000000003
3.0
3.2
3.4000000000000004
3.6
3.8000000000000003
4.0
4.2
4.4
4.6000000000000005
4.800000000000001


Published: 2022-09-11 02:08:43

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.