对于大商,整数除法 (//
) 似乎不一定等于正则除法的下限 (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/