由于 Python 整数除法运算符 (a//b) 总是返回一个值,该值可以安全地存储在 int 中而不会丢失精度(无论值是a 和 b),为什么以下是正确的?
如果一个或两个操作数都是 float 类型,则此运算符返回 float。
只有当两个操作数都是 int 类型时,此运算符才会返回 int。
如果 __floordiv__ 的每个实现都返回一个 int 会不会更一致?
请您参考如下方法:
Python 声明两个参数都被强制转换为通用类型。来自Numeric types documentation :
Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where integer is narrower than floating point, which is narrower than complex.
并且来自 Arithmetic conversions section 表达式文档:
When a description of an arithmetic operator below uses the phrase “the numeric arguments are converted to a common type,” this means that the operator implementation for built-in types works as follows:
- If either argument is a complex number, the other is converted to complex;
- otherwise, if either argument is a floating point number, the other is converted to floating point;
- otherwise, both must be integers and no conversion is necessary.
和 Binary arithmetic operations section (包括楼层划分)然后使用该措辞:
The
/(division) and//(floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type.
楼层划分算子也不异常(exception);所有算术运算符的行为完全相同。
如果楼层划分的行为有所不同,它将是此规则的异常(exception),从而产生不一致的行为,而不是更加一致。
