Python 3 int除法运算符返回浮点数吗? [英] Python 3 int division operator is returning a float?
问题描述
在我的一项任务中,我遇到了一个奇怪的实现,我很好奇它是错误还是设计的行为。
In one of my assignments I came across a weird implementation, and I was curious if it's a bug or the designed behavior.
在Python 3中,除以 /
返回浮点数,而 //
表示整数除法,应返回整数。我发现尽管在整数除法时两个值中的任何一个都是浮点数,它将返回一个浮点数。
In Python 3, division by /
returns a floating point number, and //
means integer division and should return an integer. I've discovered though that if either of the values is a float when doing integer division, it will return a float.
示例:
# These all work as expected
10 / 2
-> 5.0
11 / 2
-> 5.5
10 // 2
-> 5
11 // 2
-> 5
# Here things start to get weird
10.0 // 2
-> 5.0
10 // 2.0
-> 5.0
11.0 // 2
-> 5.0
该应该表现为这种行为吗?如果是这样,为什么会这样运行?
Is this supposed to behave this way? If so, why does it behave this way?
推荐答案
来自 PEP-238 ,它引入了新的部门(重点是我的部门):
From PEP-238, which introduced the new division (emphasis mine):
地板分割的语义
地板除法将在所有Python数值类型
中实现,并将具有以下语义:
Semantics of Floor Division
Floor division will be implemented in all the Python numeric types, and will have the semantics of:
a // b == floor(a/b)
除了结果类型将是 a 和$ b的通用类型$ b b 在操作之前被强制。
except that the result type will be the common type into which a and b are coerced before the operation.
具体来说,如果 a 和 b 是同一类型, a // b
也将是该类型。如果输入是不同类型,则它们首先是
使用与所有其他
算术运算符相同的规则强制转换为通用类型。
Specifically, if a and b are of the same type, a//b
will be of that type too. If the inputs are of different types, they are first
coerced to a common type using the same rules used for all other
arithmetic operators.
尤其是,如果 a 和 b 均为整数或多头,则结果的
类型和值与这些类型的经典除法(对于混合输入类型,包括
; int // long
和 long // int
都会使
都返回一个long)。
In particular, if a and b are both ints or longs, the result has the
same type and value as for classic division on these types (including
the case of mixed input types; int//long
and long//int
will both
return a long).
对于浮点输入,结果为浮点数。例如:
3.5//2.0 == 1.0
复数, //
引发异常,因为不允许
复数的 floor()
。
For complex numbers, //
raises an exception, since floor()
of a
complex number is not allowed.
对于用户定义的类和扩展类型,所有语义都取决于该类或类型的实现。
For user-defined classes and extension types, all semantics are up to the implementation of the class or type.
是的,它的行为应该是这样。 //
表示整数除法,应该返回整数 -不完全,它表示地板除法并应返回等于整数(您总是希望(a // b).is_integer()
为真,其中任何一个操作数都是浮点数)。
So yes, it is supposed to behave that way. "//
means integer division and should return an integer" - not quite, it means floor division and should return something equal to an integer (you'd always expect (a // b).is_integer()
to be true where either operand is a float).
这篇关于Python 3 int除法运算符返回浮点数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!