How to use a decimal range() step value?

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

    To counter the float precision issues, you could use the Decimal module.

    This demands an extra effort of converting to Decimal from int or float while writing the code, but you can instead pass str and modify the function if that sort of convenience is indeed necessary.

    from decimal import Decimal
    
    
    def decimal_range(*args):
    
        zero, one = Decimal('0'), Decimal('1')
    
        if len(args) == 1:
            start, stop, step = zero, args[0], one
        elif len(args) == 2:
            start, stop, step = args + (one,)
        elif len(args) == 3:
            start, stop, step = args
        else:
            raise ValueError('Expected 1 or 2 arguments, got %s' % len(args))
    
        if not all([type(arg) == Decimal for arg in (start, stop, step)]):
            raise ValueError('Arguments must be passed as ')
    
        # neglect bad cases
        if (start == stop) or (start > stop and step >= zero) or \
                              (start < stop and step <= zero):
            return []
    
        current = start
        while abs(current) < abs(stop):
            yield current
            current += step
    

    Sample outputs -

    from decimal import Decimal as D
    
    list(decimal_range(D('2')))
    # [Decimal('0'), Decimal('1')]
    list(decimal_range(D('2'), D('4.5')))
    # [Decimal('2'), Decimal('3'), Decimal('4')]
    list(decimal_range(D('2'), D('4.5'), D('0.5')))
    # [Decimal('2'), Decimal('2.5'), Decimal('3.0'), Decimal('3.5'), Decimal('4.0')]
    list(decimal_range(D('2'), D('4.5'), D('-0.5')))
    # []
    list(decimal_range(D('2'), D('-4.5'), D('-0.5')))
    # [Decimal('2'),
    #  Decimal('1.5'),
    #  Decimal('1.0'),
    #  Decimal('0.5'),
    #  Decimal('0.0'),
    #  Decimal('-0.5'),
    #  Decimal('-1.0'),
    #  Decimal('-1.5'),
    #  Decimal('-2.0'),
    #  Decimal('-2.5'),
    #  Decimal('-3.0'),
    #  Decimal('-3.5'),
    #  Decimal('-4.0')]
    

提交回复
热议问题