How to use a decimal range() step value?

前端 未结 30 2177
醉话见心
醉话见心 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

    NumPy is a bit overkill, I think.

    [p/10 for p in range(0, 10)]
    [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
    

    Generally speaking, to do a step-by-1/x up to y you would do

    x=100
    y=2
    [p/x for p in range(0, int(x*y))]
    [0.0, 0.01, 0.02, 0.03, ..., 1.97, 1.98, 1.99]
    

    (1/x produced less rounding noise when I tested).

提交回复
热议问题