简体   繁体   中英

How do I tell if a solution to a set of equations is valid in Math.NET Numerics?

Trying to solve a system of linear equations using Math.NET Numerics but wont know in advance whether they will have a valid solution.

For example, the equations x + y = 10, x = 3, y = 7, have an obvious solution.

In Math.NET, we programmed this as (making it a square matrix)

var A1 = Matrix<double>.Build.SparseOfArray(new double[,]
{
    { 1, 1, 0 },
    { 1, 0, 0 },
    { 0, 1, 0 },
});
var b1 = Vector<double>.Build.Dense(new double[] { 10, 3, 7 });

We tried to solve it like this

var x1 = A1.Solve(b1);

But that returns NaN for x and y.

Following the advice online we tried the solve it like this

var p1 = A1.PseudoInverse();
var x1 = p1 * b1;

Which returned the correct solutions x = 3 and y = 7.

We then tried an inconsistent set of equations x + y = 10, x = 3, y = 6, and to our surprise it produced a solution x = 3.333333, y = 6.333333 with no indication this is not a valid solution.

How do we get Math.NET to solve a set of equations, which may be inconsistent or may have some redundancy, and get some indication that the solution is valid?

How do I tell if a solution to a set of equations is valid in Math.NET Numerics?

The same way you validate your solutions on paper at college. Just put the answer into the initial equation, calculate some actual result and compare it with the expected one. For comparation use Euclidean norm of their difference for example. The closer to zero it is, the better the answer is.

var expected = b1;
var actual = A1 * x1;
var eps = (expected - actual).L2Norm();
Console.WriteLine(eps);

For x + y = 10, x = 3, y = 7 it gives 8.881784197001252E-16 . Almost zero. That's quite wonderful.

For x + y = 10, x = 3, y = 6 it is 0.577350269189626 . Not so good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM