前言
过去在Python中使用到Round()函数时,都是默认四舍五入,直到刚才一小段代码运行出错,最后追溯到了Round()函数,网上冲浪外加官方文档才发现它水很深;鉴于之前经常出现遇到问题,网上搜索后解决完了,后续再遇到又一脸懵的情况,决定今后遇到的问题尽量记录下来,作为笔记使用
一、Pytho中的 round()函数
作为Python内置函数,可以根据给定的精度对一个数字进行舍入操作
二、文档
1.
目录
help(round)
解释器自带帮助文档结果如下
Help on built-in function round in module builtins:
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.
2.官方文档
链接:round (Python function, in Built-in Functions)
round(number, ndigits=None)
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is
None
, it returns the nearest integer to its input.For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both
round(0.5)
andround(-0.5)
are0
,andround(1.5)
is2
). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted orNone
. Otherwise, the return value has the same type as number.For a general Python object
number
,round
delegates tonumber.__round__
.
Note:The behavior of round() for floats can be surprising: for example,
round(2.675, 2)
gives2.67
instead of the expected2.68
. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.
文档中提到,对于
round(x, n)
会将x以(a为整数)的形式舍入到最接近x的情况;
例如round(3.141,1)中,要求精度,现在需要决定的舍(a=31)还是入(a=32)
按照最接近的原则,最后决定直接舍去要求精度以外数位的值,保留1位小数3.1即可,这与小学学过的四舍五入无异,但是在一样接近时(精度后只有一位且为5)时,应当使结果向偶数舍入
l=[1.5,2.5,3.5,4.5]
for i in l:
b = round(i)
print(f'{i} {b}')
运行结果符合文档所述
1.5 2
2.5 2
3.5 4
4.5 4
但关于偶数有一个小问题,只有整数才存在奇偶的问题,即文档中只说明了n未声明/为None/=0时的结果,针对其它情况,测试一番
-
n<0
l=[1.5,2.5,3.5,4.5]
for i in l:
b = round(10*i,-1)
print(f'{i} {b}')
1.5 20.0
2.5 20.0
3.5 40.0
4.5 40.0
从运行结果可看出,n<0时仍然符合上述说明,但此时的偶数指的是中a的奇偶,这点需要注意
-
n>0
l=[1.5,2.5,3.5,4.5]
for i in l:
a = round(i/10+0.001,1)
b = round(i/10,1)
print(f'{i/10} {b} | {i/10+0.001} {a}')
0.15 0.1 | 0.151 0.2
0.25 0.2 | 0.251 0.3
0.35 0.3 | 0.351 0.4
0.45 0.5 | 0.451 0.5
运行结果表明n>0时偶数规则不再适用,此时遵循“四舍六入、50舍51入”的规则
总结