How to use a decimal range() step value?

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

    I am only a beginner, but I had the same problem, when simulating some calculations. Here is how I attempted to work this out, which seems to be working with decimal steps.

    I am also quite lazy and so I found it hard to write my own range function.

    Basically what I did is changed my xrange(0.0, 1.0, 0.01) to xrange(0, 100, 1) and used the division by 100.0 inside the loop. I was also concerned, if there will be rounding mistakes. So I decided to test, whether there are any. Now I heard, that if for example 0.01 from a calculation isn't exactly the float 0.01 comparing them should return False (if I am wrong, please let me know).

    So I decided to test if my solution will work for my range by running a short test:

    for d100 in xrange(0, 100, 1):
        d = d100 / 100.0
        fl = float("0.00"[:4 - len(str(d100))] + str(d100))
        print d, "=", fl , d == fl
    

    And it printed True for each.

    Now, if I'm getting it totally wrong, please let me know.

提交回复
热议问题