当 decimal>=1 时,pandas / numpy round() 如何工作?

How does pandas / numpy round() work when decimal>=1?

我有一个pandas系列

In [1]: import pandas as pd
In [2]: s = pd.Series([1.3, 2.6, 1.24, 1.27, 1.45])

我需要对数字进行四舍五入。

In [4]: s.round(1)
Out[4]:
0    1.3
1    2.6
2    1.2
3    1.3
4    1.4
dtype: float64

1.27有效,但是1.45四舍五入为1.4,是不是float类型丢精度的问题?如果是,我该如何处理这个问题?

This isn't a bug but it is because, most decimal numbers cannot be represented exactly as a float.

https://www.programiz.com/python-programming/methods/built-in/round

另一种舍入方式是:

int(number*10^precission+0.5)

但是,您可能会 运行 遇到类似的问题,因为谁知道 1.45 更接近 1.4499999.. 还是 1.4500...1

一般来说,round()经常因为浮点数的估计不准确而失败。

但在这种情况下,这是因为为了平衡舍入误差,所有数字的一半(偶数)都向下舍入的约定。

You can pretty easily disable this behavior:

round(x[, n]) x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.