首页 文章

Python整数除法产生浮点数

提问于
浏览
160
Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/2
1.0

这是有意的吗?我强烈记得早期版本返回 int/int=int ?我该怎么办,是否有一个新的分区运算符或者我必须总是演员?

4 回答

  • 223

    看看PEP-238:更改分部操作员

    //运营商可以明确地请求楼层划分 .

  • 19

    哎呀,马上找到 2//2 .

  • 50

    希望它可以立即帮助某人 .

    Python 2.7和Python 3中除法运算符的行为

    在Python 2.7中:默认情况下,除法运算符将返回整数输出 .

    得到的结果是双 multiple 1.0 到"dividend or divisor"

    100/35 => 2 #(Expected is 2.857142857142857)
    (100*1.0)/35 => 2.857142857142857
    100/(35*1.0) => 2.857142857142857
    

    在Python 3中

    // => used for integer output
    / => used for double output
    
    100/35 => 2.857142857142857
    100//35 => 2
    100.//35 => 2.0    # floating-point result if divsor or dividend real
    
  • 30

    接受的答案已经提到PEP 238 . 我只想在幕后为那些对正在发生的事情感兴趣而不阅读整个PEP的人添加一个快速浏览 .

    Python将 +-*/ 之类的运算符映射到特殊函数,例如 a + b 相当于

    a.__add__(b)
    

    关于Python 2中的除法,默认情况下只有 / 映射到 __div__ ,结果取决于输入类型(例如 intfloat ) .

    Python 2.2引入了 __future__ 特性 division ,它以下列方式改变了除法语义(TL; PEP 238的DR):

    • / 映射到 __truediv__ ,必须"return a reasonable approximation of the mathematical result of the division"(引自PEP 238)

    • // 映射到 __floordiv__ ,它应返回 / 的覆盖结果

    使用Python 3.0,PEP 238的更改成为默认行为,Python的对象模型中没有更多特殊方法 __div__ .

    如果你想在Python 2和Python 3中使用相同的代码

    from __future__ import division
    

    并坚持 /// 的PEP 238语义 .

相关问题