【问题标题】:recursive function for subset sum problem with floating-point numbers浮点数子集和问题的递归函数
【发布时间】:2019-11-07 10:45:59
【问题描述】:

我为subset sum problem 做了一个递归函数f(s,x),当从值集合x 中选择元素时,它能够生成所有唯一组合,这些组合总和为目标总和's'。

例如,假设x <- c(2,4,8,10)s <- 10表示目标总和,下面有函数f

f <- function(s, x, xhead = head(x,1), r = c()) {
  if (s == 0) {
    return(list(r))
  } else {
    x <- sort(x,decreasing = T)
    return(unlist(lapply(x[x<=min(xhead,s)], function(k) f(s-k, x[x<= s-k], min(k,head(x[x<=s-k],1)), c(r,k))),recursive = F)) 
  }
}

我可以得到子集和的所有组合,即,

> f(s,x)
[[1]]
[1] 10

[[2]]
[1] 8 2

[[3]]
[1] 4 4 2

[[4]]
[1] 4 2 2 2

[[5]]
[1] 2 2 2 2 2

上面的函数适用于xs 的整数。 然而,当我将xs 缩小10,即xs 的浮点数时,输出变为不受欢迎的:

> f(s/10,x/10)
[[1]]
[1] 1

但是想要的输出应该是这样的

> Map(function(v) v/10, f(s,x))
[[1]]
[1] 1

[[2]]
[1] 0.8 0.2

[[3]]
[1] 0.4 0.4 0.2

[[4]]
[1] 0.4 0.2 0.2 0.2

[[5]]
[1] 0.2 0.2 0.2 0.2 0.2

我怀疑我的函数f 在处理浮点数时一定有问题,但经过多次试验后未能修复。任何人都可以帮助我解决这个问题,而无需对函数 f 进行大的更改吗?

提前感谢任何帮助!

【问题讨论】:

    标签: r precision subset-sum


    【解决方案1】:

    您可以在减法中使用round 并设置小数点

    f <- function(s, x, xhead = head(x,1), r = c()) {
      if (s == 0) {
        return(list(r))
      } else {
        x <- sort(x,decreasing = T)
        return(unlist(lapply(x[x<=min(xhead,s)], function(k) f(round(s-k, 4), x[x<= round(s-k, 4)], min(k,head(x[x<= round(s-k, 4)],1)), c(r,k))),recursive = F)) 
      }
    }
    
    f(s/10,x/10)
    

    返回所需的输出:

    [[1]]
    [1] 1
    
    [[2]]
    [1] 0.8 0.2
    
    [[3]]
    [1] 0.4 0.4 0.2
    
    [[4]]
    [1] 0.4 0.2 0.2 0.2
    
    [[5]]
    [1] 0.2 0.2 0.2 0.2 0.2
    

    【讨论】:

      猜你喜欢
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多