Round with integer division

前端 未结 6 732
情书的邮戳
情书的邮戳 2021-01-07 17:47

Is there is a simple, pythonic way of rounding to the nearest whole number without using floating point? I\'d like to do the following but with integer arithmetic:

6条回答
  •  猫巷女王i
    2021-01-07 18:16

    Inspired by zhmyh's answer answer, which is

    q, r = divmod(total, surplus)
    skip = q + int(bool(r)) # rounds to next greater integer (always ceiling)
    

    , I came up with the following solution:

    q, r = divmod(total, surplus) 
    skip = q + int(2 * r >= surplus) # rounds to nearest integer (floor or ceiling)
    

    Since the OP asked for rounding to the nearest whole number, zhmhs's solution is in fact slightly incorrect, because it always rounds to the next greater whole number, while my solution works as demanded.

    (If you feel that my answer should better have been an edit or comment on zhmh's answer, let me point out that my suggested edit for it was rejected, because it should better have been a comment, but I do not have enough reputation yet for commenting!)

    In case you wonder how divmod is defined: According to its documentation

    For integers, the result is the same as (a // b, a % b).

    We therefore stick with integer arithmetic, as demanded by the OP.

提交回复
热议问题