R语言 求列中几个数字的精确或最近似和

v9tzhpje  于 2022-12-24  发布在  其他
关注(0)|答案(2)|浏览(147)

我有一个列,列中有一长串数字(40 k),并且有一个特定的结果(100,000)。
有没有一种方法(在求解器,Python,R等),给予我的解决方案,求和一些选定的数字,给我的预期结果(100,000)或最近似的。
简短示例:

mzmfm0qo

mzmfm0qo1#

我是手动完成的,因为数字量太大了,但是在Python 3中,对于少量数字的答案是:

mylist = r"C:path\of\the\file.csv"

import pandas as pd

df = pd.read_csv(mylist)

def subset_sum(numbers, target, partial=[]):
    s = sum(partial)

    # check if the partial sum is equals to target
    if s == target: 
        print ("sum(%s)=%s" % (partial, target))
    
    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i+1:]
        subset_sum(remaining, target, partial + [n]) 
   

if _name_ == "_main_":
    subset_sum(#List,#target)
flseospp

flseospp2#

这可以作为MIP(混合整数规划)问题来解决:

min |deviation| 
 subject to sum(i, value[i]*x[i]) = target + deviation
 x[i] ∈ {0,1}

一些代码来测试这个:

import cvxpy as cp
import random

#
# problem size
#
N = 40000
I = range(N)

#
# problem data
#
target = 100000
random.seed(12345)
p = [random.randrange(0,10000) for i in I]

#
# model
#
x = cp.Variable(N,boolean=True)
deviation = cp.Variable(1)
prob = cp.Problem(cp.Minimize(cp.abs(deviation)),[p@x==target+deviation])

#
# solve and reporting
#
prob.solve(solver=cp.CBC,verbose=True)

xsum = 0
for i in I:
    if x[i].value > 0.5:
        print(f"i:{i} value:{p[i]}")
        xsum += p[i]
print(f"sum={xsum}")

结果:

-------------------------------------------------------------------------------
                                    Summary
-------------------------------------------------------------------------------
(CVXPY) Dec 23 12:35:28 PM: Problem status: optimal
(CVXPY) Dec 23 12:35:28 PM: Optimal value: 1.438e-11
(CVXPY) Dec 23 12:35:28 PM: Compilation took 9.899e-02 seconds
(CVXPY) Dec 23 12:35:28 PM: Solver (including time spent in interface) took 1.156e+00 seconds
i:6 value:9273
i:9 value:6112
i:11 value:7093
i:13 value:9209
i:15 value:9063
i:3857 value:9209
i:9341 value:2035
i:12413 value:9209
i:15914 value:2035
i:15989 value:2126
i:16558 value:2035
i:16965 value:2035
i:24271 value:63
i:24290 value:7093
i:26791 value:624
i:30330 value:6752
i:32612 value:6752
i:34308 value:219
i:36798 value:9063
sum=100000

相关问题