1 {-# LANGUAGE FlexibleInstances #-}
2 {-# LANGUAGE RebindableSyntax #-}
4 -- | The 'Normed' class represents elements of a normed vector
5 -- space. We define instances for all common numeric types.
11 import NumericPrelude hiding ( abs )
12 import Algebra.Absolute ( abs )
13 import qualified Algebra.Absolute as Absolute ( C )
14 import qualified Algebra.Algebraic as Algebraic ( C )
15 import Algebra.Algebraic ( root )
16 import qualified Algebra.RealField as RealField ( C )
17 import qualified Algebra.ToInteger as ToInteger ( C )
18 import qualified Algebra.ToRational as ToRational ( C )
19 import Data.Vector.Fixed ( S, Z )
20 import qualified Data.Vector.Fixed as V (
24 import Data.Vector.Fixed.Boxed ( Vec )
26 import Linear.Vector ( element_sum )
29 -- | Instances of the 'Normed' class know how to compute their own
30 -- p-norms for p=1,2,...,infinity.
33 norm_p :: (ToInteger.C c, Algebraic.C b, Absolute.C b) => c -> a -> b
34 norm_infty :: (RealField.C b) => a -> b
36 -- | The \"usual\" norm. Defaults to the 2-norm.
37 norm :: (Algebraic.C b, Absolute.C b) => a -> b
38 norm = norm_p (2 :: Integer)
40 -- Define instances for common numeric types.
41 instance Normed Integer where
42 norm_p _ = abs . fromInteger
43 norm_infty = abs . fromInteger
45 instance Normed Rational where
46 norm_p _ = abs . fromRational'
47 norm_infty = abs . fromRational'
49 instance Epsilon e => Normed (BigFloat e) where
50 norm_p _ = abs . fromRational' . toRational
51 norm_infty = abs . fromRational' . toRational
53 instance Normed Float where
54 norm_p _ = abs . fromRational' . toRational
55 norm_infty = abs . fromRational' . toRational
57 instance Normed Double where
58 norm_p _ = abs . fromRational' . toRational
59 norm_infty = abs . fromRational' . toRational
62 -- | 'Normed' instance for vectors of length zero. These are easy.
63 instance Normed (Vec Z a) where
64 norm_p _ = const (fromInteger 0)
65 norm_infty = const (fromInteger 0)
68 -- | 'Normed' instance for vectors of length greater than zero. We
69 -- need to know that the length is non-zero in order to invoke
70 -- V.maximum. We will generally be working with n-by-1 /matrices/
71 -- instead of vectors, but sometimes it's convenient to have these
76 -- >>> import Data.Vector.Fixed (mk3)
77 -- >>> import Linear.Vector (Vec3)
78 -- >>> let b = mk3 1 2 3 :: Vec3 Double
79 -- >>> norm_p 1 b :: Double
81 -- >>> norm b == sqrt 14
83 -- >>> norm_infty b :: Double
86 instance (V.Arity n, Absolute.C a, ToRational.C a, Ord a)
87 => Normed (Vec (S n) a) where
89 (root p') $ element_sum $ V.map element_function x
91 element_function y = fromRational' $ (toRational y)^p'
94 norm_infty x = fromRational' $ toRational $ V.maximum $ V.map abs x