这是一个典型的 MSF 优化公式:
using Microsoft.SolverFoundation.Services;
SolverContext context = SolverContext.GetContext();
Model model = context.CreateModel();
//decisions
Decision xs = new Decision(Domain.Real, "Number_of_small_chess_boards");
Decision xl = new Decision(Domain.Real, "Number_of_large_chess_boards");
model.AddDecisions(xs, xl);
//constraints
model.AddConstraints("limits", 0 <= xs, 0 <= xl);
model.AddConstraint("BoxWood", 1 * xs + 3 * xl <= 200);
model.AddConstraint("Lathe", 3 * xs + 2 * xl <= 160);
//Goals
model.AddGoal("Profit", GoalKind.Maximize, 5 * xs + 20 * xl);
// This doesn't work!
// model.AddGoal("Profit", GoalKind.Maximize, objfunc(xs, xl));
Solution sol = context.Solve(new SimplexDirective());
Report report = sol.GetReport();
Console.WriteLine(report);
是否可以使用单独的方法而不是像“5 * xs + 20 * xl”这样的语句作为目标函数?例如,像下面这样的方法?如何?
// this method doesn't work!
static double objfunc(Decision x, Decision y)
{
return 5 * x.ToDouble() + 20 * y.ToDouble();
}
最佳答案
它是如此简单:
static Term objfunc(Decision x, Decision y)
{
return 5 * x + 20 * y;
}
该函数必须返回一个
double
而不是返回 Term
。