Math.Net 中的三角求解器
TriangularSolver in Math.Net
是否有与 Java ejml 库中的 TriangularSolver 等效的任何现有求解器?
特别是我需要一个使用正向替换求解下三角矩阵的函数。
我最终自己实现了一个下三角矩阵求解器:
public static Vector<double> SolveLower(this Matrix<double> a, Vector<double> b)
{
if (a.RowCount != a.ColumnCount)
{
throw new ArgumentException("Matrix must be square.");
}
if (a.RowCount != b.Count)
{
throw new ArgumentException("Matrix row and Vector must be the same length.");
}
var x = b.Clone();
double sum;
for (int row = 0; row < a.ColumnCount; row++)
{
sum = x.At(row);
for (int col = 0; col < row; col++)
{
sum -= a.At(row, col) * x.At(col);
}
x[row] = sum / a.At(row, row);
}
return x;
}
测试方法:
[TestMethod]
public void TestSolveLowerMatrix()
{
var a = Matrix<double>.Build.DenseOfArray(new double[,] { { 3, 0, 0, 0},
{ -1, 1, 0, 0 },
{ 3, -2, -1, 0 },
{ 1, -2, 6, 2}});
var b = Vector<double>.Build.DenseOfArray(new double[] { 5, 6, 4, 2 });
var x = a.SolveLower(b);
// Verify results are valid
var expected = Vector<double>.Build.Dense(new double[] { 5 / 3.0, 23 / 3.0, -43 / 3.0, 305 / 6.0 });
Assert.AreEqual(expected.ToString(), x.ToString());
// Double check that A*x = b
Assert.AreEqual(b.ToString(), (a * x).ToString());
}
是否有与 Java ejml 库中的 TriangularSolver 等效的任何现有求解器?
特别是我需要一个使用正向替换求解下三角矩阵的函数。
我最终自己实现了一个下三角矩阵求解器:
public static Vector<double> SolveLower(this Matrix<double> a, Vector<double> b)
{
if (a.RowCount != a.ColumnCount)
{
throw new ArgumentException("Matrix must be square.");
}
if (a.RowCount != b.Count)
{
throw new ArgumentException("Matrix row and Vector must be the same length.");
}
var x = b.Clone();
double sum;
for (int row = 0; row < a.ColumnCount; row++)
{
sum = x.At(row);
for (int col = 0; col < row; col++)
{
sum -= a.At(row, col) * x.At(col);
}
x[row] = sum / a.At(row, row);
}
return x;
}
测试方法:
[TestMethod]
public void TestSolveLowerMatrix()
{
var a = Matrix<double>.Build.DenseOfArray(new double[,] { { 3, 0, 0, 0},
{ -1, 1, 0, 0 },
{ 3, -2, -1, 0 },
{ 1, -2, 6, 2}});
var b = Vector<double>.Build.DenseOfArray(new double[] { 5, 6, 4, 2 });
var x = a.SolveLower(b);
// Verify results are valid
var expected = Vector<double>.Build.Dense(new double[] { 5 / 3.0, 23 / 3.0, -43 / 3.0, 305 / 6.0 });
Assert.AreEqual(expected.ToString(), x.ToString());
// Double check that A*x = b
Assert.AreEqual(b.ToString(), (a * x).ToString());
}