整数除法舍入 [英] Round with integer division

查看:74
本文介绍了整数除法舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的 Pythonic 方法可以在不使用浮点数的情况下四舍五入到最接近的整数?我想做以下但使用整数运算:

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:

skip = int(round(1.0 * total / surplus))

==============

==============

@John:浮点数不能跨平台重现.如果您希望您的代码在不同平台上通过测试,那么您需要避免浮点(或在您的测试中添加一些 hacky espilon 内容并希望它有效).以上可能很简单,在大多数/所有平台上都是一样的,但我宁愿不做这个决定,因为完全避免浮点更容易.这不符合 Python 的精神"是怎么回事?

@John: Floating point is not reproducible across platforms. If you want your code to pass tests across different platforms then you need to avoid floating point (or add some hacky espilon stuff to your tests and hope it works). The above may be simple enough that it would be the same on most/all platforms, but I'd rather not make that determination as it is easier to avoid floating point altogether. How is that "not in the spirit of Python"?

推荐答案

你可以很简单地做到这一点:

You can do this quite simply:

(n + d//2)//d,其中 n 是被除数,d 是除数.

(n + d // 2) // d, where n is the dividend and d is the divisor.

替代方案,如 (((n <<1)//d) + 1) >>1 或等效的 (((n * 2)//d) + 1)//2 在最近的 CPython 中可能更慢,其中 int 是像旧的 long 一样实现.

Alternatives like (((n << 1) // d) + 1) >> 1 or the equivalent (((n * 2) // d) + 1) // 2 may be SLOWER in recent CPythons, where an int is implemented like the old long.

简单方法执行 3 次变量访问、1 次常量加载和 3 次整数运算.复杂的方法执行 2 次变量访问、3 次常量加载和 4 次整数运算.整数运算可能需要时间,这取决于所涉及数字的大小.局部函数的变量访问不涉及查找".

The simple method does 3 variable accesses, 1 constant load, and 3 integer operations. The complicated methods do 2 variable accesses, 3 constant loads, and 4 integer operations. Integer operations are likely to take time which depends on the sizes of the numbers involved. Variable accesses of function locals don't involve "lookups".

如果您真的对速度非常渴望,请进行基准测试.否则,KISS.

If you are really desparate for speed, do benchmarks. Otherwise, KISS.

这篇关于整数除法舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆