How to use a decimal range() step value?

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

    This is my solution to get ranges with float steps.
    Using this function it's not necessary to import numpy, nor install it.
    I'm pretty sure that it could be improved and optimized. Feel free to do it and post it here.

    from __future__ import division
    from math import log
    
    def xfrange(start, stop, step):
    
        old_start = start #backup this value
    
        digits = int(round(log(10000, 10)))+1 #get number of digits
        magnitude = 10**digits
        stop = int(magnitude * stop) #convert from 
        step = int(magnitude * step) #0.1 to 10 (e.g.)
    
        if start == 0:
            start = 10**(digits-1)
        else:
            start = 10**(digits)*start
    
        data = []   #create array
    
        #calc number of iterations
        end_loop = int((stop-start)//step)
        if old_start == 0:
            end_loop += 1
    
        acc = start
    
        for i in xrange(0, end_loop):
            data.append(acc/magnitude)
            acc += step
    
        return data
    
    print xfrange(1, 2.1, 0.1)
    print xfrange(0, 1.1, 0.1)
    print xfrange(-1, 0.1, 0.1)
    

    The output is:

    [1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0]
    [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1]
    [-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0]
    

提交回复
热议问题