python np.round() 十进制选项大于 2
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22261843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python np.round() with decimal option larger than 2
提问by Rain Lee
Python has default round() function, but I was programming with cython and want to replace pythonic code with numpy function. However, I got the following results when experimenting it in terminal.
Python 有默认的 round() 函数,但我用 cython 编程,想用 numpy 函数替换 pythonic 代码。但是,在终端中进行实验时,我得到了以下结果。
>>> np.around(1.23456789)
1.0
>>> np.around(1.23456789, decimals=0)
1.0
>>> np.around(1.23456789, decimals=1)
1.2
>>> np.around(1.23456789, decimals=2)
1.23
>>> np.around(1.23456789, decimals=3)
1.2350000000000001
>>> np.around(1.23456789, decimals=4)
1.2345999999999999
Which is kind of strange, and I still want the following "desired" result:
这有点奇怪,我仍然想要以下“期望”的结果:
>>> round(1.23456789,3)
1.235
>>> round(1.23456789,4)
1.2346
采纳答案by Mark Ransom
The problem is that the binary representation of floating point numbers can't exactly represent most decimal numbers. For example, the two closest values to 1.235 are:
问题是浮点数的二进制表示不能完全表示大多数十进制数。例如,最接近 1.235 的两个值是:
- 1.2350000000000000976996261670137755572795867919921875
- 1.234999999999999875655021241982467472553253173828125
- 1.2350000000000000976996261670137755572795867919921875
- 1.234999999999999875655021241982467472553253173828125
Since the first one is closer to the desired value, it's the one you get.
由于第一个更接近所需的值,因此它是您获得的值。
When you let the Python environment display a floating-point number, it uses the __repr__conversion function which shows enough digits to unambiguously identify the number. If you use the __str__conversion instead, it should round the number to a reasonable number of digits. At least that's what the built-in floattype does, I assume numpy works the same way. The printfunction calls __str__by default, so try this:
当您让 Python 环境显示浮点数时,它使用__repr__转换函数显示足够的数字来明确标识该数字。如果您改用__str__转换,它应该将数字四舍五入到合理的位数。至少这就是内置float类型所做的,我假设 numpy 的工作方式相同。该print函数__str__默认调用,所以试试这个:
print np.around(1.23456789, decimals=3)
For applications where you absolutely need decimal accuracy there is the decimalmodule. It can do rounding as well.
对于绝对需要十进制精度的应用程序,有decimal模块。它也可以进行舍入。

