python - 整数除法总是等于正除法的下限吗?

标签 python integer division floating-accuracy integer-division

对于大商,整数除法 (//) 似乎不一定等于正则除法的下限 (math.floor(a/b) )。

根据 Python 文档 (https://docs.python.org/3/reference/expressions.html - 6.7),

floor division of integers results in an integer; the result is that of mathematical division with the ‘floor’ function applied to the result.

然而,

math.floor(648705536316023400 / 7) = 92672219473717632

648705536316023400 // 7 = 92672219473717628

'{0:.10f}'.format(648705536316023400/7) 产生 '92672219473717632.0000000000',但小数部分的最后两位应该是 28 而不是 32。

最佳答案

您的测试用例中的商不相等的原因是在 math.floor(a/b) 的情况下,结果是使用浮点运算(IEEE-754 64-bit ),这意味着有一个最大精度。您拥有的商大于 253 限制,超过该限制浮点不再精确到单位。

然而,对于整数除法,Python 使用其无限的整数范围,因此结果是正确的。

另见 "Semantics of True Division" in PEP 238 :

Note that for int and long arguments, true division may lose information; this is in the nature of true division (as long as rationals are not in the language). Algorithms that consciously use longs should consider using //, as true division of longs retains no more than 53 bits of precision (on most platforms).

关于python - 整数除法总是等于正除法的下限吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53891566/

相关文章:

c++ - 确定在 C++11 中实现大数的最有效字长?

javascript - 递增整数序列

mysql - SQL 在表中划分子查询

c - 除以 2 的幂并向零舍入

c# - 形状上的均匀分布算法

python - 如何使用 PostgreSQL 数据库创建基于 WebSockets 的简单 Django 聊天?

python - 如何将张量中的列设置为0?

python - Pandas:每次迭代迭代两列

python - 寻找使用 pysftp 加载/使用公共(public) ssh key 的示例

ios - 无法从 C 数组中读取整数