Python Division //

本文详细解释了Python中两种除法操作符的行为:/ 和 //。在Python 3中,/ 进行浮点数除法,而 // 执行整数除法(商不带余数)。对于Python 2.x,/ 默认执行整数除法,除非操作数之一为浮点数。文章还介绍了如何确保得到浮点数结果以及如何使用 // 操作符进行截断除法。



In Python 3, they made the / operator do a floating-point division, and added the // operator to do integer division (i.e. quotient without remainder); whereas in Python 2, the / operator was simply integer division, unless one of the operands was already a floating point number.

In Python 2.X:

>>> 10/3
3
>>> # to get a floating point number from integer division:
>>> 10.0/3
3.3333333333333335
>>> float(10)/3
3.3333333333333335

In Python 3:

>>> 10/3
3.3333333333333335
>>> 10//3
3

For further reference, see PEP238.

// is unconditionally "truncating division", e.g:

>>> 4.0//1.5
2.0

As you see, even though both operands are floats, // still truncates -- so you always know securely what it's gonna do.

Single / may or may not truncate depending on Python release, future imports, and even flags on which Python's run, e.g....:

$ python2.6 -Qold -c 'print 2/3'
0
$ python2.6 -Qnew -c 'print 2/3'
0.666666666667

As you see, single / may truncate, or it may return a float, based on completely non-local issues, up to and including the value of the -Q flag...;-).

So, if and when you know you want truncation, always use //, which guarantees it. If and when you know you don't want truncation, slap a float() around other operand and use /. Any other combination, and you're at the mercy of version, imports, and flags!-)




To complement these other answers, the // operator also offers significant (3x) performance benefits over /, presuming you want integer division.

$ python -m timeit '20.5 // 2'
100000000 loops, best of 3: 0.0149 usec per loop
$ python -m timeit '20.5 / 2'
10000000 loops, best of 3: 0.0484 usec per loop
$ python -m timeit '20 / 2'
10000000 loops, best of 3: 0.043 usec per loop
$ python -m timeit '20 // 2'
100000000 loops, best of 3: 0.0144 usec per loop

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值