📜  检查Python中正则除法的整数除法和math.floor()的相等性

📅  最后修改于: 2022-05-13 01:55:06.713000             🧑  作者: Mango

检查Python中正则除法的整数除法和math.floor()的相等性

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

例子:

Input : 269792703866060742 // 3 
Output : 89930901288686914

Input : math.floor(269792703866060742 / 3)
Output : 89930901288686912

在上面的例子中, floor division(//)的输出是 89930901288686914,math.floor 的输出是 89930901288686912。除了这个例子中的最后两位数字,即 14 和 12,所有数字都彼此相等。

示例中的商不相等的原因是,在math.floor(a/b)情况下,结果是使用浮点运算(IEEE-754 64-bit)计算的,这意味着存在最大精度。获得的商大于2^53限制,超过该限制浮点不再精确到单位。但是,对于floor division(//) , Python使用其无限整数范围,因此结果是正确的。

注意:对于 int 和 long 参数,真正的除法 (/) 可能会丢失信息;这是真正除法的本质(只要语言中没有理性)。有意识地使用 long 的算法应该考虑使用 //,因为 long 的真正除法 (/) 保留不超过 53 位的精度(在大多数平台上)。

在典型的计算机系统上,“双精度”(64 位)二进制浮点数具有 53 位的系数、11 位的指数和一个符号位。请参阅IEEE 754

例子:

# Python program to demonstrate
# equality of integer division and 
# math.floor
  
  
import math
  
  
# First case: Take x smaller
# than 2 ^ 53 . 
x = 269
y = 3
if (x // y) == math.floor(x / y):
    print("Equal Output")
      
else:
    print("Not Equal Output")
  
      
# Second case: Take x larger
# than 2 ^ 53.
x = 269792703866060742
y = 3 
if (x // y) == math.floor(x / y):
    print("Equal Output")
      
else:
    print("Not Equal Output")

输出:

Equal Output
Not Equal Output