davidm / lua-matrix

Matrices and vectors of are real, complex, and symbolic elements, implemented as Lua tables.
http://lua-users.org/wiki/LuaMatrix
Other
135 stars 54 forks source link

Inversion #9

Open A1-exe opened 6 years ago

A1-exe commented 6 years ago

The inverse of the matrix doesn't appear to be very accurate. I've noticed that whenever I try to invert a matrix it randomly adds decimals

A1-exe commented 6 years ago

I've also noticed a great change in structure after multiplication. All of this comes after trying to create a hill-code cypher using this.

bachp2 commented 5 years ago

Hi, I came across this issue when trying to do matrix inversion for my truss solver; my matrix was non-invertible but matlab came to the opposite conclusion. After looking at the source code and reading through this article https://en.wikipedia.org/wiki/Gaussian_elimination, the fault may lie in the numerical instability of gaussian method working with small numbers in matrix's entries (this may extend to your case as well). When I round them to some nice practical resolutions, everything works fine

for i=1,#K do
    for j=1,#K[1] do
    K[i][j] = tonumber(string.format("%.7f", K[i][j]))
    end
end
U = matrix.invert(K)*F
print(matrix.tostring(U,"%.3f"))

Quote from wiki: One possible problem is numerical instability, caused by the possibility of dividing by very small numbers. If, for example, the leading coefficient of one of the rows is very close to zero, then to row-reduce the matrix, one would need to divide by that number. This means that any error existed for the number that was close to zero would be amplified. Gaussian elimination is numerically stable for diagonally dominant or positive-definite matrices. For general matrices, Gaussian elimination is usually considered to be stable, when using partial pivoting, even though there are examples of stable matrices for which it is unstable.[11]

thegrb93 commented 4 years ago

@bachp2 Seeing the same issue and was driving me crazy. Thanks for pointing out the explanation.

thegrb93 commented 4 years ago

Maybe once I've recuperated, I can look into adding an LU inverse implementation. https://en.wikipedia.org/wiki/LU_decomposition#C#_code_examples

bogbasic commented 1 year ago

Solved my problem, too. Thank you.

bogbasic commented 1 year ago

for i,j in matrix.ipairs(K) do K[i][j]=tonumber(string.format("%.4f", K[i][j])) end