这个比较的结果让我吃惊(CPython 3.4):
>>> 9007199254740993 == 9007199254740993.0
False
我对the docs的理解是,左操作数应转换为float
,以匹配右操作数的类型:
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. Comparisons between numbers of mixed type use the same rule. The constructors int(), float(), and complex() can be used to produce numbers of a specific type.
这似乎没有发生:
^{pr2}$这是怎么回事?在
Python在这里并没有将整数转换为浮点;它将浮点转换为整数:
这失败了,因为int(9007199254740993.0)实际上是9007199254740992:
^{pr2}$参见^{} function 。具体而言,它面前的评论:
这两个数字的结果是:
int.__eq__(float)
路由,但返回{float.__eq__(int)
路由,该路由由float_richcompare()
处理。在在那个函数中,
v
是你的浮点值,w
是整数。以下是为该路径执行的代码选择:最后,由于涉及到的数字的大小,Python将浮点转换为整数,在这种转换中,浮点数变成了
9007199254740992
。这是因为float实际上不能准确地表示9007199254740993.0
:相关问题 更多 >
编程相关推荐