How to use a decimal range() step value?

前端 未结 30 2147
醉话见心
醉话见心 2020-11-21 22:34

Is there a way to step between 0 and 1 by 0.1?

I thought I could do it like the following, but it failed:

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


        
30条回答
  •  名媛妹妹
    2020-11-21 23:05

    Lots of the solutions here still had floating point errors in Python 3.6 and didnt do exactly what I personally needed.

    Function below takes integers or floats, doesnt require imports and doesnt return floating point errors.

    def frange(x, y, step):
        if int(x + y + step) == (x + y + step):
            r = list(range(int(x), int(y), int(step)))
        else:
            f = 10 ** (len(str(step)) - str(step).find('.') - 1)
            rf = list(range(int(x * f), int(y * f), int(step * f)))
            r = [i / f for i in rf]
    
        return r
    

提交回复
热议问题