aydarbiktimirov

Matrix determinant (Gauss)

Jun 24th, 2011
411
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Ratio
  2.  
  3. gaussStep :: [[Rational]] -> [[Rational]]
  4. gaussStep (x:xs) = x : (map (\l -> zipWith (\a b -> b - (head l) * a) (map (/ head x) x) l) xs)
  5.  
  6. findAndReplace :: (a -> Bool) -> a -> [a] -> [a] -> [a]
  7. findAndReplace p l (x:xs) result
  8.     | p x = x : result ++ [l] ++ xs
  9.     | otherwise = findAndReplace p l xs $ result ++ [x]
  10.  
  11. gaussSwap :: [[Rational]] -> [[Rational]]
  12. gaussSwap (x:xs) = findAndReplace (\x -> head x /= 0) x xs []
  13.  
  14. rationalGaussDet :: [[Rational]] -> Rational
  15. rationalGaussDet [[]] = 0
  16. rationalGaussDet [[x]] = x
  17. rationalGaussDet m@(x:xs)
  18.     | map head m == replicate (length m) 0 = 0
  19.     | head x == 0 = (toRational 0) - (rationalGaussDet $ gaussSwap m)
  20.     | otherwise = (head x) * rationalGaussDet (minor 0 (gaussStep m))
  21.  
  22. gaussDet :: (Real a) => [[a]] -> Rational
  23. gaussDet m = rationalGaussDet (map (map toRational) m)
Advertisement
Add Comment
Please, Sign In to add comment