Math.Net中的TriangularSolver

时间:2017-05-01 16:45:23

标签: mathdotnet

现有的求解器是否与Java ejml库中的TriangularSolver等效?

特别是我需要一个使用正向替换来解决下三角矩阵的函数。

1 个答案:

答案 0 :(得分:2)

我自己最终实现了一个下三角矩阵求解器:

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());
}
相关问题