一日一技:Python里面的//并不是做了除法以后取整

简介: 一日一技:Python里面的//并不是做了除法以后取整

在Python 3里面,我们做除法的时候会遇到 a/ba//b两种写法:

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

于是可能有人会认为, a//b相当于 int(a/b)

但如果再进一步测试,你会发现:

>>> int(-10/3)
-3
>>> -10 // 3
-4

看到这里,可能有人意识到, //似乎是向下取整的意思,例如 -3.33向下取整是 -4

那么我们再试一试向下取整:

>>> import math
>>> math.floor(-10/3)
-4
>>> -10//3
-4

看起来已经是这么一回事了。但是如果你把其中一个数字换成浮点数,就会发现事情并没有这么简单:

import math
>>> math.floor(-10/3.0)
-4
>>> -10//3.0
-4.0

当有一个数为浮点数的时候, //的结果也是浮点数,但是 math.floor的结果是整数。

这个原因可以参看Python PEP-238的规范:ttps://www.python.org/dev/peps/pep-0238/#semantics-of-floor-division

except that the result type will be the common type into which a and b are coerced before the operation. 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.

结果的类型将会是 ab的公共类型。如果 a是整数, b是浮点数,那么首先他们会被转换为公共类型,也就是浮点数(因为整数转成浮点数不过是末尾加上 .0,不会丢失信息,但是浮点数转换为整数,可能会把小数部分丢失。所以整数何浮点数的公共类型为浮点数),然后两个浮点数做 //以后的结果还是浮点数。


目录
相关文章
|
3月前
|
Java C++ Python
Python 教程之运算符(5)—— Python中的除法运算符
Python 教程之运算符(5)—— Python中的除法运算符
27 0
|
4月前
|
Java C++ Python
Python 教程之运算符(5)—— Python中的除法运算符
Python 教程之运算符(5)—— Python中的除法运算符
50 1
|
Python
Python经典编程习题100例:第85例:999除法
Python经典编程习题100例:第85例:999除法
42 0
|
Python
Python除法运算/、//、%、divmod
Python除法运算/、//、%、divmod
Python小数向上取整和向下取整
Python小数向上取整和向下取整
Python---试除法求质数的三种方式对比
此三种方法都是基于试除法,即不断地尝试能否整除。比如要判断自然数 x 是否质数,就不断尝试小于 x 且大于1的自然数,只要有一个能整除,则 x 是合数;否则,x 是质数。
1544 0
|
Python
python 地板除法(floor)和截断除法(trunc)
math.floor() & math.trunc() math.floor 和 math.trunc的官方不同版本的介绍如下: math.floor: python2.7: Return the floor of x as a float, the largest integer value less than or equal to x.
2207 0
|
1天前
|
机器学习/深度学习 数据挖掘 API
pymc,一个灵活的的 Python 概率编程库!
pymc,一个灵活的的 Python 概率编程库!
4 1