【问题标题】:Strange result in gaussian elimination with scilab用 scilab 进行高斯消除的奇怪结果
【发布时间】:2014-10-19 19:33:26
【问题描述】:

我用 scilab 计算高斯消元(没有部分枢轴)的函数返回了一个奇怪的结果,比如

0.083333 - 1.000000*0.083333 = -0.000000(负零,我真的不懂)

当我在矩阵中访问这个结果时,显示的数字是 - 1.388D-17。有人知道为什么会这样吗?在我的高斯消除代码下方。 A是扩展矩阵(A | b)

function [r] = gaussian_elimination(A)
//Get a tuple representing matrix dimension
[row, col] = size(A)

if  ( (row ~= 1) & (col ~= 2) ) then  

    for k = 1:row
        disp(A)
        if A(k, k) ~= 0 then   
            for i = k+1:row    
                m = real(A(i, k)/A(k, k))
                for j = 1:col
                    a = A(k, j) 
                    new_element = A(i, j) - m*a 
                    printf("New Element A(%d, %d) = %f - %f*%f = %f\n", i, j, A(i,j), m, a, new_element)

                    A(i,j) = 0
                    A(i,j) = new_element

                end   
            end
        else
            A = "Inconsistent system"
            break
        end 
    end
else
    A = A(1,1)
end
r = A

最奇怪的是,对于某些矩阵,这不会发生。

【问题讨论】:

    标签: linear-algebra scilab


    【解决方案1】:

    这是一个舍入错误。有关更多背景信息,请参阅"What Every Computer Scientist Should Know About Floating-Point Arithmetic"。简而言之:由于您所代表的数字不是 base2 并且它们以 base2 表示,因此有时很难准确地表示整个数字。找出显着性并对结果进行四舍五入。

    here的例子为例:

    // fround(x,n)
    // Round the floating point numbers x to n decimal places
    // x may be a vector or matrix// n is the integer number of places to round to
    function [y ]= fround(x,n)
        y=round(x*10^n)/10^n; 
    endfunction
    
    -->fround(%pi,5)
    ans  =     3.14159  
    

    注意:n 是小数位数,而不是数字位数。

    【讨论】:

    • 谢谢家伙,我真的怀疑这是轮错误,因为我用这个矩阵执行了代码的后半部分(反向替换),结果是正确的。我重新检查 scilab 的文档是否对此有任何说明。非常感谢。
    【解决方案2】:

    如果这只是一个舍入错误,您可以通过 clean 函数清理您的结果,该函数会将矩阵的小条目舍入为零。通过此功能,您还可以设置绝对或相对大小的清洁公差。

    clean(r);  //it will round to zero the very small elements e.g. 1.388D-17
    

    【讨论】:

      猜你喜欢
      • 2016-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 2019-08-21
      相关资源
      最近更新 更多