我正在使用accord.math来解决具有非线性约束的系统。在这个例子中,约束有4个变量, x => x[0] + x[1] + x[2] + x[3] <= 1
但是如果约束应该包括50个变量。如何在周期中构建, x => x[0] + x[1] + x[2] + ...+ x[50] <= 1
?
namespace ConsoleApplication21
{
class Program
{
static void Main(string[] args)
{
var f = new NonlinearObjectiveFunction(4, x => 0.010 * x[0] - 0.000543 * x[1] - 0.003440 * x[2] + 0.000292 * x[3]);
var constraints = new[]
{
new NonlinearConstraint(4, x => x[0] + x[1] + x[2] + x[3] <= 1),
new NonlinearConstraint(4, x => x[0] + x[1] + x[2] + x[3] >= 1),
};
var cobyla = new Cobyla(f, constraints);
bool success = cobyla.Maximize();
double minimum = cobyla.Value;
double[] solution = cobyla.Solution;
Console.WriteLine(minimum);
}
}
}
答案 0 :(得分:1)
如果你需要的只是数组中所有值的总和,你可以使用LINQ的Sum()
方法,如下所示:
new NonlinearConstraint(x.Length, x => x.Sum() >= 1)
通常,您可以使用LINQ&#39; Enumerable.Range
替换循环。例如,要将x[first]
添加到x[first+count-1]
,请使用以下表达式:
new NonlinearConstraint(
x.Length
, x => Enumerable.Range(first, count).Select(i => x[i]).Sum() >= 1
)