python round()函数解析

版权声明:本文版权归作者和CSDN共有,欢迎转载。转载时请注明原作者并保留此段声明,若不保留我也不咬你,随你了=-=。 https://blog.csdn.net/TeFuirnever/article/details/89011165

python round()函数用于返回浮点数的四舍五入值。

round(number,
	digits
)

参数:

  • number:表示输入数据,浮点数类型。

  • digits:表示保留的小数点位数,可选,默认值为 0,即如果不写的话默认保留到整数。

有人会说这是多么简单的函数。没错,除了接下来要说的两点意外,它还真是个简单的函数。

1. round的结果跟python版本有关。
2. 特殊数字round出来的结果可能未必是想要的。

例子1:

我们来看看python2和python3中有什么不同,绝对让你大跌眼镜。

1)python2

round(0.5)
> 1.0

2)python3

round(0.5)
> 0

素质三连:

【1】什么感觉?

【2】感觉不太正常是不是?

【3】说好的四舍五入呢?

通过查询python的官方文档我们发现python round()函数是这么写的:

在python2.7的doc中,round()写着,“Values are rounded to the closest multiple of 10 to the power minus ndigits;if two multiples are equally close,rounding is done away from 0。” 保留值将保留到离上一位更近的一端(四舍六入),==如果距离两端一样远,则保留到离0远的一边。==所以round(0.5)会近似到1,而round(-0.5)会近似到-1。

但是在python3.5的doc中,文档变成了,“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。” ==如果距离两边一样远,会保留到偶数的一边。==比如round(0.5)和round(-0.5)都会保留到0,而round(1.5)会保留到2。

以上是如果保留位数的后一位如果是5,且该位数后没有数字的情况下。这个时候会遵循如果距离两边一样远,会保留到偶数的一边。,如例子1,例子2:

如果保留位数的后一位如果是5,且该位数后有数字,则进上去。如例子3:

例子2:

round(2.215, 2)
> 2.21
round(2.225, 2)
> 2.23

例子3:

round(56.659, 1)
56.7
round(56.759, 1)
> 56.8

例子4:

在python2和python3的doc中都举了个相同的栗子:

round(2.675, 2)
> 2.67

原文是这么说的:

Note
The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.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()对于浮点数的行为可能令人惊讶:例如,round(2.675, 2)给出的是2.67,而不是预期的2.68。这并不是一个错误:这是一个事实的结果,即大多数小数部分不能准确地表示为浮点数。有关更多信息,请参见浮点运算:Issues and Limitations。

什么意思呢?简单来说,就是这和浮点数的精度有关。我们知道在机器中浮点数不一定能精确表达,因为换算成一串1和0后可能是无限位的,机器已经做出了截断处理。那么在机器中保存的2.675这个数字就比实际数字要小那么一点点。这一点点就导致了它离2.67要更近一点点,所以保留两位小数时就近似到了2.67。

这么看来,python round()函数的使用条件很苛刻,除非你对精确度没什么要求,不然建议你尽量避开这个函数!!!

猜你喜欢

转载自blog.csdn.net/TeFuirnever/article/details/89011165