Round with integer division

前端 未结 6 722
情书的邮戳
情书的邮戳 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条回答
  •  Happy的楠姐
    2021-01-07 18:04

    skip = (((total << 1) // surplus) + 1) >> 1
    

    Shifting things left by one bit effectively multiplies by two, shifting things right by one bit divides by two rounding down. Adding one in the middle makes it so that "rounding down" is actually rounding up if the result would have been above a .5 decimal part.

    It's basically the same as if you wrote...

    skip = int((1.0*total/surplus) + 0.5)
    

    except with everything multplied by 2, and then later divided by 2, which is something you can do with integer arithmetic (since bit shifts don't require floating point).

提交回复
热议问题