Skip to content

Instantly share code, notes, and snippets.

@Yonaba
Created June 29, 2011 16:18
Show Gist options
  • Save Yonaba/1054213 to your computer and use it in GitHub Desktop.
Save Yonaba/1054213 to your computer and use it in GitHub Desktop.
Successive Over Relaxation (SOR) Algorithm
-- SOR Algorithm implemented through Lua
function Normalize(m)
local n = 0
for i,v in ipairs(m) do
n = n + v^2
end
return math.sqrt(n)
end
local A = {
{-4,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,-11},
{1,-4,1,0,0,1,0,0,0,0,0,0,0,0,0,0,-3},
{0,1,-4,1,0,0,1,0,0,0,0,0,0,0,0,0,-3},
{0,0,1,-4,0,0,0,1,0,0,0,0,0,0,0,0,-11},
{1,0,0,0,-4,1,0,0,1,0,0,0,0,0,0,0,-8},
{0,1,0,0,1,-4,1,0,0,1,0,0,0,0,0,0,0},
{0,0,1,0,0,1,-4,1,0,0,1,0,0,0,0,0,0},
{0,0,0,1,0,0,1,-4,0,0,0,1,0,0,0,0,-8},
{0,0,0,0,1,0,0,0,-4,1,0,0,1,0,0,0,-8},
{0,0,0,0,0,1,0,0,1,-4,1,0,0,1,0,0,0},
{0,0,0,0,0,0,1,0,0,1,-4,1,0,0,1,0,0},
{0,0,0,0,0,0,0,1,0,0,1,-4,0,0,0,1,-8},
{0,0,0,0,0,0,0,0,1,0,0,0,-4,1,0,0,-10},
{0,0,0,0,0,0,0,0,0,1,0,0,1,-4,1,0,-2},
{0,0,0,0,0,0,0,0,0,0,1,0,0,1,-4,1,-2},
{0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,-4,-10},
}
local MAXITER = 10000
local N=table.getn(A)
local t = MAXITER
local w = 1.86
local ACCURACY = 1E-6
local x = {}
for k = 1,N do x[k]=0 end
repeat
t=t-1
local q = Normalize(x)
for i=1,N do
local sum=A[i][N+1]
for j=1,N do
if (i~=j) then
sum = sum-A[i][j]*x[j]
end
end
x[i]=(1-w)*x[i]+w*sum/A[i][i]
end
local p = Normalize(x)
local d = math.abs(p-q)
until (d<ACCURACY) or (t==0)
print( 'Num of iter:',MAXITER-t)
for i=1,N do
print('x['..i..']='..x[i])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment