线性方程组解算器结果(MATLAB vs Math.NET vs Python)
[1] C#:使用Math.NET库求解方程组线性方程组解算器结果(MATLAB vs Math.NET vs Python),matlab,matrix,linear-algebra,mathnet-numerics,Matlab,Matrix,Linear Algebra,Mathnet Numerics,[1] C#:使用Math.NET库求解方程组 // test solver in Math.NET var A = Matrix<double>.Build.DenseOfArray(new double[,] { {1, 1, 3}, {2, 0, 4}, {-1, 6, -1}
// test solver in Math.NET
var A = Matrix<double>.Build.DenseOfArray(new double[,] {
{1, 1, 3},
{2, 0, 4},
{-1, 6, -1}
});
Console.WriteLine(A);
var b = Vector<double>.Build.Dense(new double[] { 2, 19, 8 });
Console.WriteLine(b);
var x = A.Solve(b);//Math.NET
Console.WriteLine("Test Solver in Math.NET: " + x);
>> Test Solver in Math.NET: DenseVector 3-Double
34.5
5
-12.5
Press any key to continue . . .
[3] 在Python中,使用相同的输入并在numpy.linalg的帮助下:
In[10]:
import numpy as np
# matrix A
A = np.matrix ([[1, 1, 3],[2, 0, 4],[-1, 6, -1]])
# vector b
b = np.array([2, 19, 8])
b.shape = (3,1)
# attempt to solve Ax=b
z = np.linalg.solve(A,b)
z
Out[10]:
array([[ 34.5],
[ 5. ],
[-12.5]])
[4] C#(Math.NET)和Python的结果似乎是一样的,而MATLAB的结果却大不相同,这是为什么呢?C#和Python的例子解决了方程A*x=b
,而MATLAB的例子解决了x*A=b
MATLAB示例可以更改为通过转换b并使用\
而不是/
来求解A*x=b
Math.NET(和Python)示例可以通过转置A来求解
x*A=b
,即A.Transpose().solve(b)
而不是A.solve(b)
当你转置b时,你在MATLAB中得到了什么,即b=[2;19;8]
@ChristophRüegg:你不能这样做,行应该是相同的维度。我得到错误:“使用/矩阵维度的错误必须一致。”啊,是的,应该是B\A
,而不是B/A
。没错。然而,解A.X=B意味着X=B/A,对吗?c#和Python代码解决了这个特定系统的问题。在MATLAB中,B/A
solvex*A=B
,而不是A*x=B
In[10]:
import numpy as np
# matrix A
A = np.matrix ([[1, 1, 3],[2, 0, 4],[-1, 6, -1]])
# vector b
b = np.array([2, 19, 8])
b.shape = (3,1)
# attempt to solve Ax=b
z = np.linalg.solve(A,b)
z
Out[10]:
array([[ 34.5],
[ 5. ],
[-12.5]])