如何始终在 numpy 中舍入 XX.5 [英] How to always round up a XX.5 in numpy

查看:85
本文介绍了如何始终在 numpy 中舍入 XX.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到 numpy 在四舍五入方面是无偏见的,并且它的工作方式与其设计的一样.那如果你总是将 0.5 向上取整到下一个最大的数字,那么一组四舍五入数字的平均值可能会略大于未四舍五入数字的平均值:这种偏差或漂移会对某些数值算法产生非常不利的影响,并且使它们不准确."

I read that numpy is unbiased in rounding and that it works the way its designed. That "if you always round 0.5 up to the next largest number, then the average of a bunch rounded numbers is likely to be slightly larger than the average of the unrounded numbers: this bias or drift can have very bad effects on some numerical algorithms and make them inaccurate."

不理会这些信息,假设我总是想凑数,我怎么能用numpy来做呢?假设我的数组可能很大.

Disregarding this information and assuming that I always want to round up, how can I do it in numpy? Assuming my array can be quite large.

为简单起见,假设我有数组:

For simplicity, lets assume i have the array:

import numpy as np

A = [ [10, 15, 30], [25, 134, 41], [134, 413, 51]]
A = np.array(A, dtype=np.int16)

decimal = A * .1
whole = np.round(decimal)

十进制看起来像:

[[  1.    1.5   3. ]
 [  2.5  13.4   4.1]
 [ 13.4  41.3   5.1]]

整体看起来像:

[[  1.   2.   3.]
 [  2.  13.   4.]
 [ 13.  41.   5.]]

如您所见,1.5 四舍五入为 2,2.5 也四舍五入为 2.我如何才能强制始终获得 XX.5 的四舍五入答案?我知道我可以遍历数组并使用 python round() 但这肯定会慢得多.想知道是否有办法使用 numpy 函数来做到这一点

As you can see, 1.5 rounded to 2 and 2.5 also rounded to 2. How can I force to always get a round up answer for a XX.5? I know I can loop through the array and use python round() but that would definitely be much slower. Was wondering if there is a way to do it using numpy functions

推荐答案

import numpy as np
A = [ [1.0, 1.5, 3.0], [2.5, 13.4, 4.1], [13.4, 41.3, 5.1]]
A = np.array(A)

print(A)

def rounder(x):
    if (x-int(x) >= 0.5):
        return np.ceil(x)
    else:
        return np.floor(x)

rounder_vec = np.vectorize(rounder)
whole = rounder_vec(A)
print(whole)

或者,您也可以查看numpy.ceil, numpy.floor, numpy.trunc 用于其他舍入样式

Alternatively, you can also look at numpy.ceil, numpy.floor, numpy.trunc for other rounding styles

这篇关于如何始终在 numpy 中舍入 XX.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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