gpt4 book ai didi

将数字向量舍入为整数,同时保留它们的总和

转载 作者:行者123 更新时间:2023-12-04 09:14:10 24 4
gpt4 key购买 nike

How to round floats to integers while preserving their sum?有以下answer用伪代码编写,它将向量四舍五入为整数值,从而使元素之和不变,并且舍入误差最小。我想在 R 中有效地实现这一点(即,如果可能的话,进行矢量化)。

例如,四舍五入这些数字会产生不同的总数:

set.seed(1)
(v <- 10 * runif(4))
# [1] 2.655087 3.721239 5.728534 9.082078
(v <- c(v, 25 - sum(v)))
# [1] 2.655087 3.721239 5.728534 9.082078 3.813063
sum(v)
# [1] 25
sum(round(v))
# [1] 26

answer 复制伪代码以供引用
// Temp array with same length as fn.
tempArr = Array(fn.length)

// Calculate the expected sum.
arraySum = sum(fn)

lowerSum = 0
-- Populate temp array.
for i = 1 to fn.lengthf
tempArr[i] = { result: floor(fn[i]), // Lower bound
difference: fn[i] - floor(fn[i]), // Roundoff error
index: i } // Original index

// Calculate the lower sum
lowerSum = lowerSum + tempArr[i] + lowerBound
end for

// Sort the temp array on the roundoff error
sort(tempArr, "difference")

// Now arraySum - lowerSum gives us the difference between sums of these
// arrays. tempArr is ordered in such a way that the numbers closest to the
// next one are at the top.
difference = arraySum - lowerSum

// Add 1 to those most likely to round up to the next number so that
// the difference is nullified.
for i = (tempArr.length - difference + 1) to tempArr.length
tempArr.result = tempArr.result + 1
end for

// Optionally sort the array based on the original index.
array(sort, "index")

最佳答案

以更简单的形式,我会说这个算法是:

  • 从四舍五入开始
  • 四舍五入具有最高小数部分的数字,直到达到所需的总和。

  • 这可以通过以下方式在 R 中以矢量化方式实现:
  • floor 向下舍入
  • 按小数部分排列的订单号(使用 order )
  • 使用 tail获取具有 k 个最大小数部分的元素的索引,其中 k 是我们需要增加总和以达到我们的目标值
  • 的数量。
  • 将这些指数中的每一个的输出值增加 1

  • 在代码中:
    smart.round <- function(x) {
    y <- floor(x)
    indices <- tail(order(x-y), round(sum(x)) - sum(y))
    y[indices] <- y[indices] + 1
    y
    }
    v
    # [1] 2.655087 3.721239 5.728534 9.082078 3.813063
    sum(v)
    # [1] 25
    smart.round(v)
    # [1] 2 4 6 9 4
    sum(smart.round(v))
    # [1] 25

    关于将数字向量舍入为整数,同时保留它们的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32544646/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com