From: Michael Orlitzky Date: Sun, 24 Feb 2013 14:55:10 +0000 (-0500) Subject: Get determinants working. X-Git-Url: https://gitweb.michael.orlitzky.com/?a=commitdiff_plain;h=c22f72ffaa4edec587b28a7c22aa07330349fd73;p=numerical-analysis.git Get determinants working. --- diff --git a/src/Linear/Matrix.hs b/src/Linear/Matrix.hs index 7452007..dbd321f 100644 --- a/src/Linear/Matrix.hs +++ b/src/Linear/Matrix.hs @@ -33,6 +33,7 @@ import Data.Vector.Fixed ( import qualified Data.Vector.Fixed as V ( and, fromList, + head, length, map, maximum, @@ -340,13 +341,21 @@ class (Eq a, Ring.C a) => Determined p a where determinant :: (p a) -> a instance (Eq a, Ring.C a) => Determined (Mat (S Z) (S Z)) a where - determinant m = m !!! (0,0) + determinant (Mat rows) = (V.head . V.head) rows -instance (Eq a, Ring.C a, Arity m) => Determined (Mat m m) a where - determinant _ = undefined - -instance (Eq a, Ring.C a, Arity n) +instance (Eq a, + Ring.C a, + Arity n, + Determined (Mat (S n) (S n)) a) => Determined (Mat (S (S n)) (S (S n))) a where + -- | The recursive definition with a special-case for triangular matrices. + -- + -- Examples: + -- + -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int + -- >>> determinant m + -- -1 + -- determinant m | is_triangular m = product [ m !!! (i,i) | i <- [0..(nrows m)-1] ] | otherwise = determinant_recursive @@ -356,13 +365,12 @@ instance (Eq a, Ring.C a, Arity n) det_minor i j = determinant (minor m i j) determinant_recursive = - sum [ (-1)^(1+(toInteger j)) NP.* (m' 0 j) NP.* (det_minor 0 j) + sum [ (-1)^(toInteger j) NP.* (m' 0 j) NP.* (det_minor 0 j) | j <- [0..(ncols m)-1] ] --- | Matrix multiplication. Our 'Num' instance doesn't define one, and --- we need additional restrictions on the result type anyway. +-- | Matrix multiplication. -- -- Examples: --