python中numpy模块的around方法,更好地舍入Python的NumPy.around:舍入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])

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.

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

解决方案

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. ])

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值