How do I write float instead of an integer in the step of range()?

Asked 2 years ago, Updated 2 years ago, 151 views

Can I increase from 0 to 1 by 0.1 by using range()? Since you write range(0,1,0.1), the step can only receive an integer.

for i in range(0, 1, 0.1):
    print i

for i in range(0,1,0.1): TypeError: range() integer step argument expected, got float.

python floating-point rage

2022-09-22 22:24

2 Answers

range and xrange both step can only receive int You have to use a different method.

NumPy is not a Python standard library, Allow step to float in range() with range() and similar functions.

import numpy

mylist = numpy.arange(0, 1, 0.1)
print mylist #[ 0.   0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9]
def myrange(start, end, step):
    r = start
    while(r<end):
        yield r
        r += step

for i in myrange(0,1,0.1):
    print i

This method seems to work normally in fori in myrange() If you save it as a list, a round-off error occurs, so you have to write it carefully.

mylist = [ i for i in myrange(0,1,0.1)]
print mylist #[0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999, 0.9999999999999999]


2022-09-22 22:24

The main limitation of python’s range() is it works only with integers. Python range() doesn’t support the float type.

I am not writing code here this article explained in the best way. you need to write your custom range() function which returns a range of float numbers. Python range() for float numbers


2022-09-22 22:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.