gpt4 book ai didi

c# - Microsoft Solver Foundation 为简单的 ILP 给出了错误的答案

转载 作者:行者123 更新时间:2023-12-05 04:38:21 24 4
gpt4 key购买 nike

我想使用 Microsoft Solver Foundation 解决 C# 中的二进制线性问题。我不知道为什么我得到错误的答案。目标值应该是 41.1,但我得到了 213。5 个变量的值应该是 1,其他变量应该是 0。但是我得到了很多错误值的变量。

矩阵每一行的总和应 <= 1。这是我的约束,正如您在 Constraint_arr 中看到的那样,我得到了正确的约束。

感谢您的帮助。

enter image description here enter image description here

enter image description here

定义决策变量:

        SolverContext context = SolverContext.GetContext();
Model model = context.CreateModel();
Decision[,] x = new Decision[name_column.Length, 7];

for (int i = 0; i < name_column.Length; i++)
{
for (int j = 0; j < 7; j++)
{
x[i, j] = new Decision(Domain.IntegerRange(0,1), "x" + i + j);
}
}

for (int i = 0; i < name_column.Length; i++)
{
for (int j = 0; j < 7; j++)
{
model.AddDecisions(x[i, j]);
}
}

创建约束并将其添加到模型中:

Term[] Constraint_arr = new Term[name_column.Length];
Term tempC;
int jj;
for (int i = 0; i < name_column.Length; i++)
{
tempC = 0;
for (jj= 0; jj < 7; jj++)
{
if(vars_Matrix[i,jj] == 1)
{
tempC += x[i,jj];
}
}
Constraint_arr[i] = tempC;
model.AddConstraints("constraint" + i, Constraint_arr[i] <= 1);
}

创建目标函数:

        Term objective_Func = 0;
Term tempZ;
for (int i = 0; i < name_column.Length; i++)
{
tempZ = 0;
for (int j = 0; j < 7; j++)
{
tempZ += x[i, j] * ratio[i];
}
objective_Func+= tempZ;
}

model.AddGoal("Goal", GoalKind.Maximize, objective_Func);

打印答案:

        Solution solution = context.Solve(new SimplexDirective());

Report report = solution.GetReport();

for (int i = 0; i < name_column.Length; i++)
{
for (int j = 0; j < 7; j++)
{
Console.Write(x[i, j]);
}
Console.WriteLine();
}


Console.Write("{0}", report);
Console.ReadLine();

最佳答案

以下 MiniZinc 模型的目标最大值为 14:

set of int: rows = 1..5;
set of int: cols = 1..7;
array[rows, cols] of 0..1: vars_Matrix = [|0, 0, 1, 0, 1, 1, 1
|0, 0, 1, 1, 0, 1, 1
|0, 0, 1, 0, 0, 0, 0
|0, 0, 1, 1, 0, 1, 1
|0, 0, 0, 0, 1, 0, 0|];

array[cols] of var 0..1: c;
var int: obj;

% constraint
% obj = sum(i in rows)(
% sum(j in cols) (
% c[i] * vars_Matrix[i, j]
% )
% );

constraint
obj = sum([ sum([ c[i] * vars_Matrix[i, j] | j in cols ]) | i in rows ]);

solve maximize(obj);

输出

c = array1d(1..7, [1, 1, 1, 1, 1, 1, 1]);
obj = 14;

从以下 Z3py 模型获得相同的结果:

    from z3 import *

s = Optimize()

Rows = range(5);
Cols = range(7);
vars_Matrix = [[0, 0, 1, 0, 1, 1, 1],
[0, 0, 1, 1, 0, 1, 1],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 1, 1],
[0, 0, 0, 0, 1, 0, 0]]

c = [Int("c" + str(i+1)) for i in Rows]
obj = Int("obj")

for i in Rows:
s.add(c[i] >= 0, c[i] <= 1)

s.add(obj == Sum( [ Sum( [ c[i] * vars_Matrix[i][j] for j in Cols ] ) for i in Rows ] ))

s.maximize(obj)

if sat == s.check():
print(s.model())
else:
print("No solution. Sorry!")

关于c# - Microsoft Solver Foundation 为简单的 ILP 给出了错误的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70628769/

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