更好地舍入Python的NumPy.around:舍入numpy的数组 [英] Better rounding in Python's NumPy.around: Rounding NumPy Arrays

查看:7589
本文介绍了更好地舍入Python的NumPy.around:舍入numpy的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找一种方式来圆一个numpy的阵列在一个更直观的方式。我有一些几个花车,并想将它们限制在只有少数几个小数。
这将做到这样:

I am looking for a way to round a numpy array in a more intuitive fashion. I have some of several floats, and would like to limit them to only a few decimal places. This would be done as such:

>>>import numpy as np
>>>np.around([1.21,5.77,3.43], decimals=1)
array([1.2, 5.8, 3.4])

现在想圆数字,是完全舍入步骤之间时,问题出现了。我想0.05四舍五入到0.1,但np.around设置舍入到最近的甚至的数字。这将产生以下:

Now the problem arises when trying to round numbers that are exactly between the rounding steps. I would like 0.05 rounded to 0.1, but np.around is set to round to the "nearest even number". This produces the following:

>>>np.around([0.55, 0.65, 0.05], decimals=1)
array([0.6, 0.6, 0.0])

我的问题就达,什么是舍入到最接近的数字最有效的方法,而不是简单地最近的偶数。

My question then amounts to, what is the most effective way to round to the nearest number, and not simply the nearest even number.

有关np.around更多信息,请参见其文档

For more info on np.around, see its documentation.

推荐答案

该方法围绕这是否是正确的,但如果你想要做不同的事情,你可以,例如,减去的量比舍入precision小得多,例如

The way around does this is correct, but if you want to do something different, you could, for example, subtract an amount much less than the rounding precision, for example,

def myround(a, decimals=1):
     return np.around(a-10**(-(decimals+5)), decimals=decimals)

In [22]: myround(np.array([ 1.21,  5.77,  3.43]), 1)
Out[22]: array([ 1.2,  5.8,  3.4])

In [23]: myround(np.array([ 0.55,  0.65,  0.05]), 1)
Out[23]: array([ 0.5,  0.6,  0. ])

我选择了 5 这里的原因,是由不包括奇/偶的区别,你介绍隐含约10 **的平均误差( - (十进制+ 1))/ 2所以你不应该抱怨的是错误的1 /第10000精确的错误。

The reason I chose 5 here, was that by not including the even/odd distinction, you're implicitely introducing an average error of about 10**(-(decimal+1))/2 so you shouldn't complain about an explicit error of 1/10000th of that error.

这篇关于更好地舍入Python的NumPy.around:舍入numpy的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆