Search code examples
linear-algebrascilab

Strange result in gaussian elimination with scilab


My function for calculate a gaussian elimination (without parcial pivot) with scilab are returning a strange result for operations like

0.083333 - 1.000000*0.083333 = -0.000000 (minus zero, I'm really not understand)

And when I access this result in matrix the number shown is - 1.388D-17. Someone have idea why this? Below my code for gauss elimination. A is expanded matrix (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

The most strange is that for some matrices this not happening.


Solution

  • This is a rounding error. See "What Every Computer Scientist Should Know About Floating-Point Arithmetic" for more background information. In short: since the numbers you are representing are not base2 and they are represented in base2, it is sometimes hard to accurately represent the entire number. Figure out the significance and round-off the results.

    Take for instance the example from 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  
    

    Beware: n is the number of decimals, not the number of numerical digits.