Skip to content

Instantly share code, notes, and snippets.

@Yonaba
Created June 29, 2011 16:21
Show Gist options
  • Save Yonaba/1054221 to your computer and use it in GitHub Desktop.
Save Yonaba/1054221 to your computer and use it in GitHub Desktop.
Gauss-Seidel Algorithm
-- Gauss Seidel Algorithm implemented through lua
function Norm(m)
local n = 0
for i,v in ipairs(m) do
n = n + v^2
end
return math.sqrt(n)
end
local A = {
{4,2,-4,0,2,4,0,0,0},
{2,2,-1,-2,1,3,2,0,-6},
{-4,-1,14,1,-8,-3,5,6,20},
{0,-2,1,6,-1,-4,-3,3,23},
{2,1,-8,-1,22,4,-10,-3,9},
{4,3,-3,-4,4,11,1,-4,-22},
{0,2,5,-3,-10,1,14,2,-15},
{0,0,6,3,-3,-4,2,19,45}
}
local p,q,ACCURRACY=0,0,1E-4
local n = table.getn(A)
local MAX = 10000
local t = MAX
local x = {}
for k = 1,n do x[k]=0 end
repeat
t=t-1
q = Norm(x)
for i=1,n do
local lowSum = 0
for j=1,i-1 do lowSum = lowSum+A[i][j]*x[j] end
for j=i+1,n do lowSum = lowSum+A[i][j]*x[j] end
x[i]=lowSum/A[i][i]
end
p = Norm(x)
until ((math.abs(p-q)<ACCURRACY) or (t==0))
for k,v in ipairs(x) do
print(k,v)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment