In Python, what is a good way to round towards zero in integer division?

前端 未结 8 1660
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 09:45
1/2

gives

0

as it should. However,

-1/2

gives

-1
相关标签:
8条回答
  • 2020-12-09 10:21

    Try this. Only works for numbers greater than -1

    import math
    
    x = .5
    y = -.5
    
    print math.floor(math.fabs(x))
    >> 0
    
    print math.floor(math.fabs(y))
    >> 0
    
    0 讨论(0)
  • 2020-12-09 10:24

    Correct code to do this is, in my opinion, too obscure to write as a 1-liner. So I'd put it in a function, like:

    def int0div(a, b):
        q = a // b
        if q < 0 and b*q != a:
            q += 1
        return q
    

    Good features: it works for any size of int, doesn't make any adjustment to the raw (a//b) result unless necessary, only does one division (% also does a division under the covers), and doesn't create any integers larger than the inputs. Those may or may not matter in your application; they become more important (for speed) if you use "big" integers.

    0 讨论(0)
提交回复
热议问题