Skip to content

Instantly share code, notes, and snippets.

@kotet
Last active July 5, 2018 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kotet/d49ffcf25090b98ecb03f59c2c0f4319 to your computer and use it in GitHub Desktop.
Save kotet/d49ffcf25090b98ecb03f59c2c0f4319 to your computer and use it in GitHub Desktop.
クラーメルの公式 in Haskell
import Data.List
-- 行列式
det :: [[Rational]] -> Rational
det [[a]] = a
det (a:b) | sum (map abs a) == 0 = 0
| head a == 0 = negate $ det (map (\ (a:b) -> b ++ [a]) (a:b))
| otherwise = (head a) * (det $ sub a b)
where sub a bs = map (\b -> tail(zipWith (\x y -> y - x * ((head b) / (head a))) a b)) bs
-- 小行列
minor :: Int -> Int -> [[Rational]] -> [[Rational]]
minor i j m = map (f j) (f i m)
where f a b = take (a-1) b ++ drop a b
-- 余因子行列
tilde :: [[Rational]] -> [[Rational]]
tilde m = [[ star i j m | j <- [1..(length m)]] | i <- [1..(length m)]]
where star i j m = (-1)^(i + j) * (det $ minor j i m)
-- 逆行列
inv :: [[Rational]] -> [[Rational]]
inv m = map (map (/ det m)) (tilde m)
-- クラーメルの公式
-- cramer 1 [[5,1],[3,2]] [3,2] == 4 / 7
cramer :: Int -> [[Rational]] -> [Rational] -> Rational
cramer index a b = det (transpose [if i == index then b else a' | (a',i) <- zip (transpose a) [1..]]) / det a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment