1 {-# LANGUAGE RebindableSyntax #-}
2 {-# LANGUAGE ScopedTypeVariables #-}
3 {-# LANGUAGE TypeFamilies #-}
8 import Data.Vector.Fixed (Dim, N1, Vector)
12 import NumericPrelude hiding ((*), abs)
13 import qualified NumericPrelude as NP ((*))
14 import qualified Algebra.Field as Field
16 import Debug.Trace (trace, traceShow)
18 -- | Solve the system m' * x = b', where m' is upper-triangular. Will
19 -- probably crash if m' is non-singular. The result is the vector x.
23 -- >>> let identity = fromList [[1,0,0],[0,1,0],[0,0,1]] :: Mat3 Double
24 -- >>> let b = vec3d (1,2,3)
25 -- >>> forward_substitute identity b
26 -- ((1.0),(2.0),(3.0))
27 -- >>> (forward_substitute identity b) == b
30 -- >>> let m = fromList [[1,0],[1,1]] :: Mat2 Double
31 -- >>> let b = vec2d (1,1)
32 -- >>> forward_substitute m b
35 forward_substitute :: forall a v w z.
45 forward_substitute m' b' = x'
49 -- Convenient accessor for the elements of b'.
53 -- Convenient accessor for the elements of m'.
57 -- Convenient accessor for the elements of x'.
61 -- The second argument to lambda should always be zero here, so we
63 lambda :: Int -> Int -> a
64 lambda 0 _ = (b 0) / (m 0 0)
65 lambda k _ = ((b k) - sum [ (m k j) NP.* (x j) |
66 j <- [0..k-1] ]) / (m k k)
69 -- | Solve the system m*x = b, where m is lower-triangular. Will
70 -- probably crash if m is non-singular. The result is the vector x.
74 -- >>> let identity = fromList [[1,0,0],[0,1,0],[0,0,1]] :: Mat3 Double
75 -- >>> let b = vec3d (1,2,3)
76 -- >>> backward_substitute identity b
77 -- ((1.0),(2.0),(3.0))
78 -- >>> (backward_substitute identity b) == b
81 backward_substitute :: (Show a, Field.C a,
91 backward_substitute m b =
92 forward_substitute (transpose m) b
95 -- | Solve the linear system m*x = b where m is positive definite.
97 solve_positive_definite :: Mat v w a -> Mat w z a
98 solve_positive_definite m b = x
101 -- First we solve r^T * y == b for y. Then let y=r*x
102 rx = forward_substitute (transpose r) b
103 -- Now solve r*x == b.