【问题标题】:matrix multiplication error between MATLAB and .NETMATLAB和.NET之间的矩阵乘法错误
【发布时间】: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)。即使逆算法的实现方式相同,您仍然使用两种完全不同的语言/编译器,并且在使用浮点数工作时应该预料到这种差异。

标签: c# matlab


【解决方案1】:

这两个结果似乎都很合理。 MATLAB 使用行缩减计算 inv(A)。行减少的每一步都会导致数值错误(MATLAB 将 1/3 解释为小数位数有限的小数)。因此,由于数值错误,我预计 inv(A) 的元素会偏离 10^{-16}。结果

a*inv(a) = 1 +/- 10^{-16} 沿对角线和

a*inv(a) = +/- 10^{-16} 沿非对角线

a*inv(a) 一致,等于单位矩阵加上或减去一些数值误差。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多