How to use a decimal range() step value?

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

    Here is my solution which works fine with float_range(-1, 0, 0.01) and works without floating point representation errors. It is not very fast, but works fine:

    from decimal import Decimal
    
    def get_multiplier(_from, _to, step):
        digits = []
        for number in [_from, _to, step]:
            pre = Decimal(str(number)) % 1
            digit = len(str(pre)) - 2
            digits.append(digit)
        max_digits = max(digits)
        return float(10 ** (max_digits))
    
    
    def float_range(_from, _to, step, include=False):
        """Generates a range list of floating point values over the Range [start, stop]
           with step size step
           include=True - allows to include right value to if possible
           !! Works fine with floating point representation !!
        """
        mult = get_multiplier(_from, _to, step)
        # print mult
        int_from = int(round(_from * mult))
        int_to = int(round(_to * mult))
        int_step = int(round(step * mult))
        # print int_from,int_to,int_step
        if include:
            result = range(int_from, int_to + int_step, int_step)
            result = [r for r in result if r <= int_to]
        else:
            result = range(int_from, int_to, int_step)
        # print result
        float_result = [r / mult for r in result]
        return float_result
    
    
    print float_range(-1, 0, 0.01,include=False)
    
    assert float_range(1.01, 2.06, 5.05 % 1, True) ==\
    [1.01, 1.06, 1.11, 1.16, 1.21, 1.26, 1.31, 1.36, 1.41, 1.46, 1.51, 1.56, 1.61, 1.66, 1.71, 1.76, 1.81, 1.86, 1.91, 1.96, 2.01, 2.06]
    
    assert float_range(1.01, 2.06, 5.05 % 1, False)==\
    [1.01, 1.06, 1.11, 1.16, 1.21, 1.26, 1.31, 1.36, 1.41, 1.46, 1.51, 1.56, 1.61, 1.66, 1.71, 1.76, 1.81, 1.86, 1.91, 1.96, 2.01]
    

提交回复
热议问题