我有一個約束的非線性優化問題。它可以通過Solver加載項在Microsoft Excel中解決,但是我在C#中複製它時遇到了問題。如何在C#中模擬Microsoft Excel的求解器功能(GRG非線性)?
我的問題顯示在following spreadsheet。我正在解決經典問題A x = b問題,但需要注意的是,x的所有組件必須是非負的。因此,我不使用標準線性代數,而是使用Solver和非負約束,最小化平方差的總和,並得到一個合理的解決方案。我試圖在C#中使用Microsoft Solver Foundation或Solver SDK進行復制。然而,我似乎無法與他們取得聯繫,因爲在MSF中,我無法弄清楚如何定義目標,並且通過Solver SDK,我總是可以獲得狀態「最佳」,並且所有0的解決方案絕對不是本地的最小。
這裏是我的求解器SDK代碼:
static double[][] A = new double[][] { new double[] { 1, 0, 0, 0, 0 }, new double[] { 0.760652602, 1, 0, 0, 0 }, new double[] { 0.373419404, 0.760537565, 1, 0, 0 }, new double[] { 0.136996731, 0.373331934, 0.760422587, 1, 0 }, new double[] { 0.040625222, 0.136953801, 0.373244464, 0.76030755, 1 } };
static double[][] b = new double[][] { new double[] { 2017159 }, new double[] { 1609660 }, new double[] { 837732.8125 }, new double[] { 330977.3125 }, new double[] { 87528.38281 } };
static void Main(string[] args)
{
using(Problem problem = new Problem(Solver_Type.Minimize, 5, 0))
{
problem.VarDecision.LowerBound.Array = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0 };
problem.VarDecision.UpperBound.Array = new double[] { Constants.PINF, Constants.PINF, Constants.PINF, Constants.PINF, Constants.PINF };
problem.Evaluators[Eval_Type.Function].OnEvaluate += new EvaluateEventHandler(SumOfSquaredErrors);
problem.ProblemType = Problem_Type.OptNLP;
problem.Solver.Optimize();
Optimize_Status status = problem.Solver.OptimizeStatus;
Console.WriteLine(status.ToString());
foreach(double x in problem.VarDecision.FinalValue.Array)
{
Console.WriteLine(x);
}
}
}
static Engine_Action SumOfSquaredErrors(Evaluator evaluator)
{
double[][] x = new double[evaluator.Problem.Variables[0].Value.Array.Length][];
for(int i = 0; i < x.Length; i++)
{
x[i] = new double[1] { evaluator.Problem.Variables[0].Value.Array[i] };
}
double[][] b_calculated = MatrixMultiply(A, x);
double sum_sq = 0.0;
for(int i = 0; i < b_calculated.Length; i++)
{
sum_sq += Math.Pow(b_calculated[i][0] - b[i][0], 2);
}
evaluator.Problem.FcnObjective.Value[0] = sum_sq;
return Engine_Action.Continue;
}
static double[][] MatrixMultiply(double[][] left, double[][] right)
{
if(left[0].Length != right.Length)
{
throw new ArgumentException();
}
double[][] sum = new double[left.Length][];
for(int i = sum.GetLowerBound(0); i <= sum.GetUpperBound(0); i++)
{
sum[i] = new double[right[i].Length];
}
for(int i = 0; i < sum.Length; i++)
{
for(int j = 0; j < sum[0].Length; j++)
{
for(int k = 0; k < right.Length; k++)
{
sum[i][j] += left[i][k] * right[k][j];
}
}
}
return sum;
}
我沒有對微軟求解基金會的任何代碼,因爲我不認爲目標函數可以在一行內寫完就和它doesn」允許像Solver SDK那樣的代表。
那麼給我們展示你的代碼怎麼樣?如果你收回所有0,那麼你可能做錯了什麼。 –
你走了。以前會這樣做,但是由於我使用了專有的Matrix類,所以我不得不寫一個快速而且髒的矩陣乘法函數。 –
想要查看微軟求助代碼的基礎代碼 – FistOfFury