为了完整起见,让我在你的问题中再添加两个函数,并解释float(int(x))、math.floor(x)、round(x)和math.ceil(x)之间的区别。
让我们从一个问题开始:“哪个整数最能代表数字 1.6?”
我们有两个可能的答案(1 和 2),但是为什么一个答案可能比另一个更好的原因有很多:
-
int(1.6)==1:这就是你去掉小数后得到的结果。
-
math.floor(1.6)==1:小于2,不完整的不算。
-
round(1.6)==2:因为 2 比 1 更接近。
-
math.ceil(1.6)==2: 不止1。开始一个零件,你要付全价。
让我们让 python 打印一张漂亮的表格,其中包含不同 x 值得到的结果:
from math import floor, ceil
tab='\t'
print 'x \tint\tfloor\tround\tceil'
for x in (1.0, 1.1, 1.5, 1.9, -1.1, -1.5, -1.9):
print x, tab, int(x), tab, floor(x), tab, round(x), tab, ceil(x)
这是输出:
x int floor round ceil
1.0 1 1.0 1.0 1.0
1.1 1 1.0 1.0 2.0
1.5 1 1.0 2.0 2.0
1.9 1 1.0 2.0 2.0
-1.1 -1 -2.0 -1.0 -1.0
-1.5 -1 -2.0 -2.0 -1.0
-1.9 -1 -2.0 -2.0 -1.0
你看到这四个函数中没有一个是相等的。
-
floor 向负无穷取整:它始终选择可能的最低答案:floor(1.99)==1 和 floor(-1.01)==-2。
-
ceil 趋向无穷大:它总是选择可能的最高答案:ceil(1.01)==2 和 ceil(-1.99)=-1。
-
int 向零舍入:对于积极的 x,它就像 floor,对于消极的 x,它就像 ceil。
-
round 舍入到最接近的可能解决方案:round(1.49)=1 和 round(1.51)==2。当x 正好在两个数字之间时,round(x) 从零开始舍入:round(1.5)==2 和 round(-1.5)==-2。这与 int(x) 在这种情况下所做的相反。
注意int(x) 总是返回一个整数 --- 其他函数返回浮点数。