summaryrefslogtreecommitdiff
path: root/packages/base/src/Internal/Random.hs
diff options
context:
space:
mode:
Diffstat (limited to 'packages/base/src/Internal/Random.hs')
-rw-r--r--packages/base/src/Internal/Random.hs81
1 files changed, 81 insertions, 0 deletions
diff --git a/packages/base/src/Internal/Random.hs b/packages/base/src/Internal/Random.hs
new file mode 100644
index 0000000..8c792eb
--- /dev/null
+++ b/packages/base/src/Internal/Random.hs
@@ -0,0 +1,81 @@
1-----------------------------------------------------------------------------
2-- |
3-- Module : Numeric.LinearAlgebra.Random
4-- Copyright : (c) Alberto Ruiz 2009-14
5-- License : BSD3
6-- Maintainer : Alberto Ruiz
7-- Stability : provisional
8--
9-- Random vectors and matrices.
10--
11-----------------------------------------------------------------------------
12
13module Internal.Random (
14 Seed,
15 RandDist(..),
16 randomVector,
17 gaussianSample,
18 uniformSample,
19 rand, randn
20) where
21
22import Internal.Vectorized
23import Internal.Vector
24import Internal.Matrix
25import Internal.Numeric
26import Internal.Algorithms
27import System.Random(randomIO)
28
29-- | Obtains a matrix whose rows are pseudorandom samples from a multivariate
30-- Gaussian distribution.
31gaussianSample :: Seed
32 -> Int -- ^ number of rows
33 -> Vector Double -- ^ mean vector
34 -> Matrix Double -- ^ covariance matrix
35 -> Matrix Double -- ^ result
36gaussianSample seed n med cov = m where
37 c = dim med
38 meds = konst' 1 n `outer` med
39 rs = reshape c $ randomVector seed Gaussian (c * n)
40 m = rs `mXm` cholSH cov `add` meds
41
42-- | Obtains a matrix whose rows are pseudorandom samples from a multivariate
43-- uniform distribution.
44uniformSample :: Seed
45 -> Int -- ^ number of rows
46 -> [(Double,Double)] -- ^ ranges for each column
47 -> Matrix Double -- ^ result
48uniformSample seed n rgs = m where
49 (as,bs) = unzip rgs
50 a = fromList as
51 cs = zipWith subtract as bs
52 d = dim a
53 dat = toRows $ reshape n $ randomVector seed Uniform (n*d)
54 am = konst' 1 n `outer` a
55 m = fromColumns (zipWith scale cs dat) `add` am
56
57-- | pseudorandom matrix with uniform elements between 0 and 1
58randm :: RandDist
59 -> Int -- ^ rows
60 -> Int -- ^ columns
61 -> IO (Matrix Double)
62randm d r c = do
63 seed <- randomIO
64 return (reshape c $ randomVector seed d (r*c))
65
66-- | pseudorandom matrix with uniform elements between 0 and 1
67rand :: Int -> Int -> IO (Matrix Double)
68rand = randm Uniform
69
70{- | pseudorandom matrix with normal elements
71
72>>> disp 3 =<< randn 3 5
733x5
740.386 -1.141 0.491 -0.510 1.512
750.069 -0.919 1.022 -0.181 0.745
760.313 -0.670 -0.097 -1.575 -0.583
77
78-}
79randn :: Int -> Int -> IO (Matrix Double)
80randn = randm Gaussian
81