Skip to content

Instantly share code, notes, and snippets.

@xdcrafts
Created September 27, 2012 06:25
Show Gist options
  • Save xdcrafts/3792497 to your computer and use it in GitHub Desktop.
Save xdcrafts/3792497 to your computer and use it in GitHub Desktop.
Implementation of Gauss-Seidel method for solving of system of linear algebraic equations.
-- file Slae.GaussSeidel xdCrafts 27.09.2012
module
Slae.GaussSeidel (
solveWithAccuracy,
solveWithAccuracy1
)
where
-- http://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method
-- function that represents Xi(k+1)
-- k1 - number of iteration
-- i - nuber of variable X
-- c - array of coefficients
-- f - array of free coefficients
x :: (Floating floating) => Int -> Int -> [[floating]] -> [floating] -> floating
x 0 _ _ _ = 0
x k1 i c f =
(1 / getC i i) * (getF i - sum getK1List - sum getKList)
where
getC m n = c !! m !! n
getF m = f !! m
getK1List = [getC i j * x k1 j c f | j <- [0 .. i - 1]]
getKList = [getC i j * x (k1 - 1) j c f | let n = length f - 1, j <- [i + 1 .. n]]
-- http://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method
-- function that represents solution of system of linear algebraic equations.
-- k - number of iteration
-- c - array of coefficients
-- f - array of free coefficients
solve :: (Floating floating) => Int -> [[floating]] -> [floating] -> [floating]
solve k c f =
[x k i c f | let n = length f - 1, i <- [0..n]]
-- function that calculates absolute differences between two vectors of values
(|-|) :: (Floating floating) => [floating] -> [floating] -> [floating]
[] |-| _ = []
_ |-| [] = []
(x:xs) |-| (y:ys) = abs (y - x) : (xs |-| ys)
-- http://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method
-- function that represents solution of system of linear algebraic equations.
-- e - accuracy
-- k - initial iteration number of iteration
-- c - array of coefficients
-- f - array of free coefficients
solveWithAccuracy :: (Floating floating, Ord floating) => floating -> Int -> [[floating]] -> [floating] -> [floating]
solveWithAccuracy e k c f
| accuracy < e = solutionK1
| otherwise = solveWithAccuracy e (k + 1) c f
where
accuracy = maximum (solutionK |-| solutionK1)
solutionK = solve k c f
solutionK1 = solve (k + 1) c f
-- http://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method
-- function that represents solution of system of linear algebraic equations.
-- e - accuracy
-- c - array of coefficients
-- f - array of free coefficients
solveWithAccuracy1 :: (Floating floating, Ord floating) => floating -> [[floating]] -> [floating] -> [floating]
solveWithAccuracy1 e c f = solveWithAccuracy e 1 c f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment