【发布时间】:2016-11-17 21:08:58
【问题描述】:
注意:本题与my previous question here on Matrix right division有关
当我在 MATLAB 和 C# 中比较以下示例的最终结果时,我注意到存在明显差异。为什么会这样?
求矩阵求逆的结果似乎吻合,但 A*A^-1 似乎还差得很远。
MATLAB 中的示例:
>> a = [1 2 3; 4 5 6; 7 8 10]
a =
1 2 3
4 5 6
7 8 10
>> inv(a)
ans =
-0.6667 -1.3333 1.0000
-0.6667 3.6667 -2.0000
1.0000 -2.0000 1.0000
>> z = mtimes(a, inv(a))
>> z
z =
1.0000e+00 -4.4409e-16 -1.1102e-16
1.3323e-15 1.0000e+00 -2.2204e-16
2.2204e-15 -2.6645e-15 1.0000e+00
C# 中的相同数据: using CSML Matrix Library
//using CSML Matrix Library
public static Matrix operator *(Matrix A, Matrix B)
{
if (A.ColumnCount != B.RowCount)
throw new ArgumentException("Inner matrix dimensions must agree.");
Matrix C = new Matrix(A.RowCount, B.ColumnCount);
for (int i = 1; i <= A.RowCount; i++)
{
for (int j = 1; j <= B.ColumnCount; j++)
{
C[i, j] = Dot(A.Row(i), B.Column(j));
}
}
return C;
}
Console.WriteLine(e1);
1; 2; 3; \
4; 5; 6; \
7; 8; 10; \
Console.WriteLine(e1.Inverse());
-0.666666666666667; -1.33333333333333; 1; \
-0.666666666666669; 3.66666666666667; -2; \
1; -2; 1; \
Console.WriteLine(e1 * e1.Inverse());
0.999999999999999; 1.77635683940025E-15; -8.88178419700125E-16; \
-5.32907051820075E-15; 1.00000000000001; -3.5527136788005E-15; \
-1.06581410364015E-14; 3.5527136788005E-15; 0.999999999999996; \
【问题讨论】:
-
差异似乎很小 - 在机器精度的顺序上,
eps(1)。即使逆算法的实现方式相同,您仍然使用两种完全不同的语言/编译器,并且在使用浮点数工作时应该预料到这种差异。