[英]solve an underdetermined linear equations system in c#
I need to solve an underdetermined linear equations system in c#.我需要解决 c# 中的欠定线性方程组。 For example
例如
Underdetermined linear equations system:欠定线性方程组:
x + 3 = y + z x + 3 = y + z
x + w = 2 x + w = 2
Result:结果:
x = r1 x = r1
y = -r2 + r1 + 3 y = -r2 + r1 + 3
z = r2 z = r2
w = 2 - r1 w = 2 - r1
and now I initialize r1 and r2 with 3 and 4 to get one of my retults.现在我用 3 和 4 初始化 r1 和 r2 以获得我的结果之一。
I try to use Math.Net in c# like this我尝试像这样在 c# 中使用 Math.Net
using MathNet.Numerics.LinearAlgebra;
namespace SolveLinearEquations
{
class Program
{
static void Main(string[] args)
{
var A = Matrix<double>.Build.DenseOfArray(new double[,] {
{ 1, -1, -1, 0 },
{ 1, 0, 0, 1 }
});
var B = Vector<double>.Build.Dense(new double[] { -3, 2 });
var X = A.Solve(B);
}
}
}
but I take an exception like this但我接受这样的例外
System.ArgumentException: 'Matrix dimensions must agree: 2x4.'
Can't Math.Net solve an underdetermined linear equations system or...? Math.Net 不能解决一个欠定的线性方程组或...? What's the best solution for this?
什么是最好的解决方案?
I solved it like this我这样解决了
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double.Solvers;
namespace SolveLinearEquations
{
class Program
{
static void Main(string[] args)
{
var A = Matrix<double>.Build.DenseOfArray(new double[,] {
{ 1, -1, -1, 0 },
{ 1, 0, 0, 1 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 }
});
var B = Vector<double>.Build.Dense(new double[] { -3, 2, 0, 0 });
var x = A.SolveIterative(B, new MlkBiCgStab());
}
}
}
but now I have a problem.但现在我有一个问题。 This solution gives me an unique value for each variable and sometimes this values are negative but I need positive values for each variable.
这个解决方案为每个变量提供了一个唯一值,有时这个值是负数,但我需要每个变量的正值。 what should I do?
我应该怎么办?
Here are three ways to try.这里有三种方法可以尝试。
1) Change your undetermined systen by adding another equation. 1)通过添加另一个方程来改变你未确定的系统。 For example, if you are getting r1<0, then add the equation r1 = a for some a >= 0;
例如,如果您得到 r1<0,则添加等式 r1 = a for some a >= 0;
2) Recast your problem as a linear programming problem. 2)将您的问题重铸为线性规划问题。 This would give you the ability to add constraints, and also you can build the objective function to get a result that you like.
这将使您能够添加约束,并且您可以构建目标 function 以获得您喜欢的结果。 So far as I know, this is not directly supported by MathNet, but there is an attempt at a solution here: http://type-nat.ch/post/lp-simplex-draft/
据我所知,这不是 MathNet 直接支持的,但这里有一个解决方案的尝试: http://type-nat.ch/post/lp-simplex-draft/
3) Use a general purpose minimizing function. 3) 使用通用最小化 function。 Define the function to be minimized as the sum of error terms based on the system's equations.
根据系统方程,将要最小化的 function 定义为误差项的总和。 For example, change y=mx+b to (y-(mx+b))^2.
例如,将 y=mx+b 更改为 (y-(mx+b))^2。 For constraints, add a conditional error term, eg c = if (r1<0, r1^2, else 0)
对于约束,添加条件错误项,例如 c = if (r1<0, r1^2, else 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.