lua-matrix
lua-matrix copied to clipboard
Inversion
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
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.
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]
@bachp2 Seeing the same issue and was driving me crazy. Thanks for pointing out the explanation.
Maybe once I've recuperated, I can look into adding an LU inverse implementation. https://en.wikipedia.org/wiki/LU_decomposition#C#_code_examples
Solved my problem, too. Thank you.
for i,j in matrix.ipairs(K) do K[i][j]=tonumber(string.format("%.4f", K[i][j])) end