public void QuadraticConstructorTest()
{
double[,] quadraticTerms =
{
{ 1, 2, 3 },
{ 2, 5, 6 },
{ 3, 6, 9 },
};
double[] linearTerms = { 1, 2, 3 };
var target = new QuadraticObjectiveFunction(quadraticTerms, linearTerms);
var function = target.Function;
var gradient = target.Gradient;
FiniteDifferences fd = new FiniteDifferences(3, function);
double[][] x =
{
new double[] { 1, 2, 3 },
new double[] { 3, 1, 4 },
new double[] { -6 , 5, 9 },
new double[] { 31, 25, 246 },
new double[] { -0.102, 0, 10 },
};
{ // Function test
for (int i = 0; i < x.Length; i++)
{
double expected = 0.5 *
(x[i].Multiply(quadraticTerms)).InnerProduct(x[i])
+ linearTerms.InnerProduct(x[i]);
double actual = function(x[i]);
Assert.AreEqual(expected, actual, 1e-8);
}
}
{ // Gradient test
for (int i = 0; i < x.Length; i++)
{
double[] expected = fd.Compute(x[i]);
double[] actual = gradient(x[i]);
for (int j = 0; j < actual.Length; j++)
Assert.AreEqual(expected[j], actual[j], 1e-8);
}
}
}