考虑值在 0 和 1 之间的随机数组,例如:
[0.1,0.2,0.8,0.9]
有没有办法计算值应该向下或向上舍入到整数的点,以便最接近地匹配未舍入数组的平均值? (在上述情况下,它会处于平均水平,但这纯属巧合)
还是只是反复试验? 我在 python 中编码
谢谢你的帮助
最佳答案
将它们相加,然后四舍五入。这就是你想要的 1 的数量。舍入,所以你得到那么多 1。
def rounding_point(l):
# if the input is sorted, you don't need the following line
l = sorted(l)
ones_needed = int(round(sum(l)))
# this may require adjustment if there are duplicates in the input
return 1.0 if ones_needed == len(l) else l[-ones_needed]
如果结果证明对列表进行排序过于昂贵,您可以使用 selection algorithm像快速选择。不过,Python 没有内置快速选择函数,所以除非您的输入足够大,以至于快速选择的渐近优势超过高度优化的 C 排序算法的常数因子优势,否则请不要打扰。
关于python - 计算将数组中的值向上或向下舍入以最小影响平均值的点的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17679544/