python np.round(),十进制选项大于2 [英] python np.round() with decimal option larger than 2
问题描述
Python具有默认的round()函数,但是我正在使用cython进行编程,并且想用numpy函数替换pythonic代码.但是,在终端上进行实验时,我得到了以下结果.
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.
>>> 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
推荐答案
问题是浮点数的二进制表示不能完全表示大多数十进制数.例如,最接近1.235的两个值是:
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.2350000000000000976996261670137755572795867919921875
- 1.234999999999999875655021241982467472553253173828125
由于第一个值更接近所需值,所以它就是您获得的值.
Since the first one is closer to the desired value, it's the one you get.
当您让Python环境显示浮点数时,它使用__repr__
转换函数,该函数显示足够的数字以明确标识该数字.如果改用__str__
转换,则应将数字四舍五入为合理的位数.至少那是内置float
类型的功能,我假设numpy的工作方式相同. print
函数默认情况下会调用__str__
,因此请尝试以下操作:
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 float
type does, I assume numpy works the same way. The print
function calls __str__
by default, so try this:
print np.around(1.23456789, decimals=3)
对于绝对需要十进制精度的应用程序,有一个 decimal
模块.它也可以四舍五入.
For applications where you absolutely need decimal accuracy there is the decimal
module. It can do rounding as well.
这篇关于python np.round(),十进制选项大于2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!