public void SolveTest5()
{
// Test with singular matrix
{
// Create a matrix. Please note that this matrix
// is singular (i.e. not invertible), so only a
// least squares solution would be feasible here.
double[,] matrix =
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
};
// Define a right side vector b:
double[] rightSide = { 1, 2, 3 };
// Solve the linear system Ax = b by finding x:
double[] x = Matrix.Solve(matrix, rightSide, leastSquares: true);
// The answer should be { -1/18, 2/18, 5/18 }.
double[] expected = { -1 / 18.0, 2 / 18.0, 5 / 18.0 };
Assert.IsTrue(matrix.IsSingular());
Assert.IsTrue(expected.IsEqual(x, 1e-10));
}
{
double[,] matrix =
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
};
double[,] rightSide = { { 1 }, { 2 }, { 3 } };
Assert.IsTrue(matrix.IsSingular());
double[,] expected = { { -1 / 18.0 }, { 2 / 18.0 }, { 5 / 18.0 } };
double[,] actual = Matrix.Solve(matrix, rightSide, leastSquares: true);
Assert.IsTrue(expected.IsEqual(actual, 1e-10));
}
}