'8      !"#$%&'() * + , - . /012 3 4 5 6 7 8 9 : ; < = >?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ @Given an upward-closed predicate on an ordered Fractional type, 3 find the smallest value satisfying the predicate. @Given an upward-closed predicate on an ordered Fractional type, B find the smallest value satisfying the predicate. Starts at the F specified point with the specified stepsize, performs an exponential A search out from there until it finds an interval bracketing the E change-point of the predicate, and then performs a bisection search G to isolate the change point. Note that infinitely-divisible domains  such as 5 cannot be searched by this function because it does I not terminate until it reaches a point where further subdivision of the  interval has no effect. The  type doesn'/t expose its constructors, but I need a way to F convert them to and from their raw representation in order to sample  them. As long as  is a newtype wrapping ,  and   9 as defined here will work. Both are implemented using  .     GBuild a word out of 2 bytes. No promises are made regarding the order > in which the bytes are stuffed. Note that this means that a  RandomSource  or  MonadRandom) making use of the default definition of  getRandomWord, etc., I may return different random values on different platforms when started . with the same seed, depending on the platform's endianness. GBuild a word out of 4 bytes. No promises are made regarding the order > in which the bytes are stuffed. Note that this means that a  RandomSource  or  MonadRandom) making use of the default definition of  getRandomWord, etc., I may return different random values on different platforms when started . with the same seed, depending on the platform's endianness. GBuild a word out of 8 bytes. No promises are made regarding the order > in which the bytes are stuffed. Note that this means that a  RandomSource  or  MonadRandom) making use of the default definition of  getRandomWord, etc., I may return different random values on different platforms when started . with the same seed, depending on the platform's endianness. Pack the low 23 bits from a  into a  in the range [0,1).  Used to convert a  stdUniform  to a  stdUniform . ASame as word32ToFloat, but also return the unused bits (as the 9  least significant bits of a ) Pack the low 23 bits from a  into a  in the range [0,1).  Used to convert a  stdUniform  to a  stdUniform . @Same as wordToFloat, but also return the unused bits (as the 41  least significant bits of a ) Pack the low 52 bits from a  into a  in the range [0,1).  Used to convert a  stdUniform  to a  stdUniform . Pack a  into a ( in the range [0,1). Note that a Double's 9 mantissa is 52 bits, so this does not fill all of them. ASame as wordToDouble, but also return the unused bits (as the 12  least significant bits of a )   Names of standard  types Names of standard  types &replicateInstances standin types decls will take the template-haskell  s in decls& and substitute every instance of the  standin with  each  in types, producing one copy of the s in decls for every   in types.  For example,  Data.Random.Distribution.Uniform# has the following bit of TH code:   $( replicateInstances ''Int integralTypes [d| Y instance Distribution Uniform Int where rvar (Uniform a b) = integralUniform a b \ instance CDF Uniform Int where cdf (Uniform a b) = integralUniformCDF a b  |])MThis code takes those 2 instance declarations and creates identical ones for  every type named in .  A class for "liftable" data structures. Conceptually  an extension of  to allow deep lifting, > but lifting need not be done between monads only. Eg lifting  between  Applicatives is allowed. For instances where m and n have 'return'/'pure' defined,  these instances must satisfy  lift (return x) == return x.  This form of 8 has an extremely general type and is used primarily to  support sample1. Its excessive generality is the main reason it's not  exported from  Data.Random. RVarT is, however, an instance of  +, which in most cases is the preferred way  to do the lifting. 9This instance is incoherent with the other two. However,  by the law lift (return x) == return x, the results  must always be the same.  A ; GADT describing a request for a primitive random variate. K Random variable definitions will request their entropy via these prompts, < and entropy sources will satisfy some or all of them. The $ # function extends an entropy source''s incomplete definition to a complete L definition, essentially defining a very flexible implementation-defaulting  system.  Some possible future additions:  PrimFloat :: Prim Float  PrimInt :: Prim Int 3 PrimPair :: Prim a -> Prim b -> Prim (a :*: b)  PrimNormal :: Prim Double ! PrimChoice :: [(Double :*: a)] -> Prim a EUnfortunately, I cannot get Haddock to accept my comments about the N data constructors, but hopefully they should be reasonably self-explanatory.  !"#>This function wraps up the most common calling convention for $.  Given a predicate identifying " supported" s, and a (possibly partial)  function that maps those /s to implementations, derives a total function  mapping all s to implementations. $EThis is essentially a suite of interrelated default implementations, $ each definition making use of only " supported" primitives. It _really_ , ought to be inlined to the point where the  supported predicate 1 is able to be inlined into it and eliminated. HWhen inlined sufficiently, it should in theory be optimized down to the  static set of best6 definitions for each required primitive in terms of  only supported primitives. AHopefully it does not impose too much overhead when not inlined.  !"#$ "! #$ "!  !"#$%:A source of entropy which can be used in the given monad.  See also '. &BGenerate a random value corresponding to the specified primitive.  The 8 type has many variants, and is also somewhat unstable.  #5 is a useful function for abstracting over the type, C semi-automatically extending a partial implementation to the full   type. 'FA typeclass for monads with a chosen source of entropy. For example,  RVarD is such a monad - the source from which it is (eventually) sampled J is the only source from which a random variable is permitted to draw, so H when directly requesting entropy for a random variable these functions  are used. Occasionally one might want a % specifying the ' # instance (for example, when using runRVar). For those cases,  Data.Random.Source.Std. StdRandom provides a % that  maps to the ' instance.  For example,  State StdGen has a ' instance, so to run an  RVar (called x0 in this example) in this monad one could write  runRVar x StdRandom (or more concisely with the sample function: sample x). (BGenerate a random value corresponding to the specified primitive.  The 8 type has many variants, and is also somewhat unstable.  #5 is a useful function for abstracting over the type, C semi-automatically extending a partial implementation to the full   type.  !"%&'( '(%&"! %&&'(( )On systems that have it, /dev/,random is a handy-dandy ready-to-use source B of nonsense. Keep in mind that on some systems, Linux included, /dev/random  collects "real" entropy, and if you don'$t have a good source of it, such as C special hardware for the purpose or a *lot* of network traffic, it's pretty easy M to suck the entropy pool dry with entropy-intensive applications. For many # purposes other than cryptography, /dev/&urandom is preferable because when it  runs out of real entropy it'&ll still churn out pseudorandom data. *+)*+)+*)+**+ ,-Given a mutable reference to a  generator, we can make a  %= usable in any monad in which the reference can be modified. See Data.Random.Source.PureMT.getRandomPrimFromMTRef for more detailed J usage hints - this function serves exactly the same purpose except for a   generator instead of a PureMT generator. . Similarly, !getRandomWordFromRandomGenState x can be used in any "state" ) monad in the mtl sense whose state is a  generator. 2 Additionally, the standard mtl state monads have ' instances 9 which do precisely that, allowing an easy conversion of RVars and  other  Distribution instances to "pure" random variables.  Again, see Data.Random.Source.PureMT.getRandomPrimFromMTState for more N detailed usage hints - this function serves exactly the same purpose except  for a  generator instead of a PureMT generator. ,-.,-.,-./ Given a function for applying a  transformation to some hidden > state, this function derives a function able to generate all s 9 in the given monad. This is then suitable for either a ' or  % instance, where the supportedPrims or  supportedPrimsFrom function (respectively) is  const True. 0Given a mutable reference to a  generator, we can implement  %: for in any monad in which the reference can be modified. -Typically this would be used to define a new % instance for J some new reference type or new monad in which an existing reference type J can be modified atomically. As an example, the following instance could  be used to describe how   can be a % in the   monad:  / instance RandomSource IO (IORef PureMT) where # supportedPrimsFrom _ _ = True 9 getSupportedRandomPrimFrom = getRandomPrimFromMTRef F(note that there is actually a more general instance declared already , covering this as a a special case, so there's no need to repeat this  declaration anywhere) Example usage:  main = do J src <- newIORef (pureMT 1234) -- OR: newPureMT >>= newIORef O x <- sampleFrom src (uniform 0 100) -- OR: runRVar (uniform 0 100) src  print x 1 Similarly, getRandomPrimFromMTState x can be used in any "state" ) monad in the mtl sense whose state is a  generator. 2 Additionally, the standard mtl state monads have ' instances 9 which do precisely that, allowing an easy conversion of RVars and  other  Distribution instances to "pure" random variables (e.g., by  ErunState . sample :: Distribution d t => d t -> PureMT -> (t, PureMT).  & in the type there can be replaced by StdGen or anything else  satisfying MonadRandom (State s) => s). =For example, this module includes the following declaration:  + instance MonadRandom (State PureMT) where  supportedPrims _ _ = True 7 getSupportedRandomPrim = getRandomPrimFromMTState This describes a "standard"! way of getting random values in   A, which can then be used in various ways, for example (assuming  some RVar foo and some Word64 seed):  0 runState (runRVar foo StdRandom) (pureMT seed) 3 runState (sampleFrom StdRandom foo) (pureMT seed) % runState (sample foo) (pureMT seed) Of course, the initial + state could also be obtained by any other  convenient means, such as  if you don't care what seed is used. /01/01/01 2A token representing the "standard" entropy source in a ' P monad. Its sole purpose is to make the following true (when the types check): ! sampleFrom StdRandom === sample 32323233 4LA random variable with access to operations in an underlying monad. Useful W examples include any form of state for implementing random processes with hysteresis, F or writer monads for implementing tracing of complicated algorithms. ;For example, a simple random walk can be implemented as an 4  value:  ! rwalkIO :: IO (RVarT IO Double)  rwalkIO d = do  lastVal <- newIORef 0   let x = do 1 prev <- lift (readIORef lastVal) ( change <- rvarT StdNormal  % let new = prev + change + lift (writeIORef lastVal new)  return new   return x [To run the random walk, it must first be initialized, and then it can be sampled as usual:   do  rw <- rwalkIO # x <- sampleFrom DevURandom rw # y <- sampleFrom DevURandom rw  ... IThe same random-walk process as above can be implemented using MTL types  as follows (using !import Control.Monad.Trans as MTL):  + rwalkState :: RVarT (State Double) Double  rwalkState = do  prev <- MTL.lift get  change <- rvarT StdNormal   let new = prev + change  MTL.lift (put new)  return new ;Invocation is straightforward (although a bit noisy) if you' re used - to MTL, but there is a gotcha lurking here: sample and 7 # inherit the extreme generality of , so there will almost always H need to be an explicit type signature lurking somewhere in any client  code making use of 4( with MTL types. In this example, the  inferred type of start. would be too general to be practical, so the  signature for rwalk explicitly fixes it to . Alternatively,  in this case sample could be replaced with  \&x -> runRVarTWith MTL.lift x StdRandom. 8 rwalk :: Int -> Double -> StdGen -> ([Double], StdGen) ` rwalk count start gen = evalState (runStateT (sample (replicateM count rwalkState)) gen) start 5An opaque type modeling a "random variable" - a value 5 which depends on the outcome of some random event. 5s = can be conveniently defined by an imperative-looking style:   normalPair = do  u <- stdUniform  t <- stdUniform  let r = sqrt (-2 * log u)  theta = (2 * pi) * t   x = r * cos theta  y = r * sin theta  return (x,y)  OR by a more applicative style:   logNormal = exp <$> stdNormal >Once defined (in any style), there are several ways to sample 5s:  In a monad, using a %:  0 sampleFrom DevRandom (uniform 1 100) :: IO Int  In a monad, using a ' instance:  , sample (uniform 1 100) :: State PureMT Int 3 As a pure function transforming a functional RNG: 8 sampleState (uniform 1 100) :: StdGen -> (Int, StdGen) 6"Run" an 51 - samples the random variable from the provided  source of entropy. Typically sample,  sampleFrom or  sampleState will  be more convenient to use. 7"Runs" an 4+, sampling the random variable it defines. The ? context allows random variables to be defined using a minimal  underlying functor ( is sufficient for " conventional" random M variables) and then sampled in any monad into which the underlying functor  can be embedded (which, for , is all monads). 2The lifting is very important - without it, every 5 would have K to either be given access to the full capability of the monad in which it I will eventually be sampled (which, incidentally, would also have to be  monomorphic so you couldn' t sample one 5 in more than one monad)  or functions manipulating 5#s would have to use higher-ranked ? types to enforce the same kind of isolation and polymorphism. JFor non-standard liftings or those where you would rather not introduce a   instance, see 8. 8Like 76 but allowing a user-specified lift operation. This  operation must obey the "monad transformer" laws:   lift . return = return * lift (x >>= f) = (lift x) >>= (lift . f) EOne example of a useful non-standard lifting would be one that takes State s to > another monad with a different state representation (such as IO with the  state mapped to an IORef): C embedState :: (Monad m) => m s -> (s -> m ()) -> State s a -> m a  embedState get put = \m -> do  s <- get & (res,s) <- return (runState m s)  put s  return res 456785647845678 9:BReturn the cumulative distribution function of this distribution.  That is, a function taking x :: t" to the probability that the next G sample will return a value less than or equal to x, according to some : order or partial order (not necessarily an obvious one). In the case where t is an instance of Ord, : should correspond ( to the CDF with respect to that order. In other cases, :0 is only required to satisfy the following law:  fmap (cdf d) (rvar d) V must be uniformly distributed over (0,1). Inclusion of either endpoint is optional, # though the preferred range is (0,1]. )Note that this definition requires that : for a product type F should _not_ be a joint CDF as commonly defined, as that definition  violates both conditions. I Instead, it should be a univariate CDF over the product type. That is, E it should represent the CDF with respect to the lexicographic order  of the product. EThe present specification is probably only really useful for testing H conformance of a variable to its target distribution, and I am open to G suggestions for more-useful specifications (especially with regard to & the interaction with product types). ;A ;. is a data representation of a random variable's probability  structure. For example, in Data.Random.Distribution.Normal, the Normal  distribution is defined as:   data Normal a  = StdNormal  | Normal a a  Where the two parameters of the Normal# data constructor are the mean and J standard deviation of the random variable, respectively. To make use of  the Normal type, one can convert it to an < and manipulate it or  sample it directly:  " x <- sample (rvar (Normal 10 2))  x <- sample (Normal 10 2) A ;' is typically more transparent than an 5 K but less composable (precisely because of that transparency). There are / several practical uses for types implementing ;:  Typically, a ;/ will expose several parameters of a standard V mathematical model of a probability distribution, such as mean and std deviation for L the normal distribution. Thus, they can be manipulated analytically using M mathematical insights about the distributions they represent. For example, T a collection of bernoulli variables could be simplified into a (hopefully) smaller # collection of binomial variables. H Because they are generally just containers for parameters, they can be E easily serialized to persistent storage or read from user-supplied < configurations (eg, initialization data for a simulation). ' If a type additionally implements the 9 subclass, which extends  ;9 with a cumulative density function, an arbitrary random  variable x3 can be tested against the distribution by testing  fmap (cdf dist) x for uniformity. On the other hand, most ;#s will not be closed under all the  same operations as 54 (which, being a monad, has a fully turing-complete G internal computational model). The sum of two uniformly-distributed L variables, for example, is not uniformly distributed. To support general  composition, the ; class defines a function < to 1 construct the more-abstract and more-composable 5 representation  of a random variable. <1Return a random variable with this distribution. =QReturn a random variable with the given distribution, pre-lifted to an arbitrary 4.  Any arbitrary 5 can also be converted to an 'RVarT m' for an arbitrary m, using  either  or sample. 9:;<=;<=9:9::;<=<=>A typeclass allowing ;s and 5s to be sampled. Both may  also be sampled via 6 or 7 , but I find it psychologically I pleasing to be able to sample both using this function, as they are two @ separate abstractions for one base concept: a random variable. ?[Directly sample from a distribution or random variable, using the given source of entropy. @ESample a random variable using the default source of entropy for the % monad in which the sampling occurs. ASample a random variable in a " functional" style. Typical instantiations  of s are System.Random.StdGen or $System.Random.Mersenne.Pure64.PureMT. BSample a random variable in a "semi-functional" style. Typical instantiations  of s are System.Random.StdGen or $System.Random.Mersenne.Pure64.PureMT. >?@AB>?@AB>??@AB CA name for the "standard"$ uniform distribution over the type t,  if one exists. See also V. For  and  types that are also  , this is ; the uniform distribution over the full range of the type.  For un-  types this is not defined.  For 4 types this is a random variable in the range [0,1) 4 (that is, 0 to 1 including 0 but not including 1). DE5A definition of a uniform distribution over the type t . See also T. FAA uniform distribution defined by a lower and upper range bound.  For  and % types, the range is inclusive. For  = types the range includes the lower bound but not the upper. GCompute a random 2 value between the 2 values provided (inclusive). HCompute a random value for a  type, between  and   (inclusive for  or  types, in [, ) for Fractional types.) ICompute a random value for a   type, between  and   (inclusive) JCompute a uniform random  value in the range [0,1) KCompute a uniform random  value in the range [0,1) L:Compute a uniform random value in the range [0,1) for any  type MCompute a uniform random $ value in the range [0,1), with any  desired precision. NThe CDF of the random variable L. OfloatUniform a b computes a uniform random  value in the range [a,b) PdoubleUniform a b computes a uniform random  value in the range [a,b) QrealFloatUniform a b8 computes a uniform random value in the range [a,b) for  any  type RfixedUniform a b computes a uniform random  value in the range $ [a,b), with any desired precision. SrealUniformCDF a b# is the CDF of the random variable realFloatUniform a b. realFloatUniform a b8 computes a uniform random value in the range [a,b) for  any  type TUVGet a "standard"! uniformly distributed variable. J For integral types, this means uniformly distributed over the full range & of the type (there is no support for ). For fractional @ types, this means uniformly distributed on the interval [0,1). WGet a "standard" uniformly distributed process. J For integral types, this means uniformly distributed over the full range & of the type (there is no support for ). For fractional @ types, this means uniformly distributed on the interval [0,1). Like V2, but returns only positive or zero values. Not D exported because it is not truly uniform: nonzero values are twice $ as likely as zero on signed types. XLike V# but only returns positive values. YLike V# but only returns positive values. CDEFGHIJKLMNOPQRSTUVWXYEFTUCDVWXYGQOPRHILMJKNSCDDEFFGHIJKLMNOPQRSTUVWXYZ[\]Z[\]Z[\]Z[\][\]^DA random variable returning an arbitrary element of the given list. G Every element has equal probability of being chosen. Because it is a  pure 5 it has no memory - that is, it "draws with replacement." _GA random variable that returns the given list in an arbitrary shuffled ; order. Every ordering of the list has equal probability. `DA random variable that shuffles a list of a known length (or a list I prefix of the specified length). Useful for shuffling large lists when I the length is known in advance. Avoids needing to traverse the list to < discover its length. Each ordering has equal probability. aQA random variable that selects N arbitrary elements of a list of known length M. ^_`a^_`a^_`abcd>Generate a Bernoulli variate with the given probability. For Bool results,   bernoulli p< will return True (p*100)% of the time and False otherwise. < For numerical types, True is replaced by 1 and False by 0. e>Generate a Bernoulli process with the given probability. For Bool results,   bernoulli p< will return True (p*100)% of the time and False otherwise. < For numerical types, True is replaced by 1 and False by 0. f!A random variable whose value is  the given fraction of the time  and  the rest. ghgeneralBernoulli t f p, generates a random variable whose value is t  with probability p and f with probability 1-p. ibcdefghidefghibcbccdefghi jMCategorical distribution; a list of events with corresponding probabilities. J The sum of the probabilities must be 1, and no event should have a zero K or negative probability (at least, at time of sampling; very clever users I can do what they want with the numbers before sampling, just make sure  that if you'=re one of those clever ones, you normalize before sampling). kl Construct a kj. random variable from a list of probabilities 7 and categories, where the probabilities all sum to 1. m Construct a kj- random process from a list of probabilities 7 and categories, where the probabilities all sum to 1. n Construct a kj2 distribution from a list of weighted categories, 0 where the weights do not necessarily sum to 1. o Construct a kj0 distribution from a list of observed outcomes. N Equivalent events will be grouped and counted, and the probabilities of each K event in the returned distribution will be proportional to the number of  occurrences of that event. pLike ;, but for the probabilities of a categorical distribution. qCAdjust all the weights of a categorical distribution so that they  sum to unity. rPSimplify a categorical distribution by combining equivalent categories (the new J category will have a probability equal to the sum of all the originals). sLSimplify a categorical distribution by combining equivalent events (the new B event will have a weight equal to the sum of all the originals). N The comparator function is used to identify events to combine. Once chosen, K the events and their weights are combined by the provided probability and  event aggregation function. jklmnopqrs lmnojkpqrs jkklmnopqrstuvwxytuvwxytuvwxytuuvwxyz8A data structure containing all the data that is needed  to implement Marsaglia & Tang's "ziggurat" algorithm for 1 sampling certain kinds of random distributions. IThe documentation here is probably not sufficient to tell a user exactly J how to build one of these from scratch, but it is not really intended to 9 be. There are several helper functions that will build {zs. 1 The pathologically curious may wish to read the  source. J That is the ultimate specification of the semantics of all these fields. {|?The X locations of each bin in the distribution. Bin 0 is the  infinite one. >In the case of bin 0, the value given is sort of magical - x[0] is  defined to be V/ f(R). It')s not actually the location of any bin, G but a value computed to make the algorithm more concise and slightly A faster by not needing to specially-handle bin 0 quite as often. 2 If you really need to know why it works, see the   source or "the literature" - it's a fairly standard setup. }The ratio of each bin's Y value to the next bin' s Y value ~"The Y value (zFunc x) of each bin 0An RVar providing a random tuple consisting of: / a bin index, uniform over [0,c) :: Int (where c is the " number of bins in the tables) 9 a uniformly distributed fractional value, from -1 to 1 , if not mirrored, from 0 to 1 otherwise. This is provided as a single 5 because it can be implemented > more efficiently than naively sampling 2 separate values - a > single random word (64 bits) can be efficiently converted to B a double (using 52 bits) and a bin number (using up to 12 bits),  for example. The distribution for the final "virtual" bin 7 (the ziggurat algorithm does not handle distributions @ that wander off to infinity, so another distribution is needed  to handle the last "bin" that stretches to infinity) 8A copy of the uniform RVar generator for the base type,  so that Distribution Uniform t is not needed when sampling 7 from a Ziggurat (makes it a bit more self-contained). 9The (one-sided antitone) PDF, not necessarily normalized 5A flag indicating whether the distribution should be 6 mirrored about the origin (the ziggurat algorithm it < its native form only samples from one-sided distributions. ; By mirroring, we can extend it to symmetric distributions " such as the normal distribution) *Sample from the distribution encoded in a {z data structure. "Build the tables to implement the "ziggurat algorithm" devised by  Marsaglia &7 Tang, attempting to automatically compute the R and V  values.  Arguments: 4 flag indicating whether to mirror the distribution : the (one-sided antitone) PDF, not necessarily normalized  the inverse of the PDF  the number of bins ! R, the x value of the first bin  V, the volume of each bin  an RVar providing the  random tuple 9 an RVar sampling from the tail (the region where x > R) "Build the tables to implement the "ziggurat algorithm" devised by  Marsaglia &7 Tang, attempting to automatically compute the R and V  values. Arguments are the same as for , with an additional B argument for the tail distribution as a function of the selected  R value. EBuild a lazy recursive ziggurat. Uses a lazily-constructed ziggurat B as its tail distribution (with another as its tail, ad nauseum).  Arguments: 4 flag indicating whether to mirror the distribution : the (one-sided antitone) PDF, not necessarily normalized  the inverse of the PDF , the integral of the PDF (definite, from 0) : the estimated volume under the PDF (from 0 to +infinity) = the chunk size (number of bins in each layer). 64 seems to  perform well in practice.  an RVar providing the  random tuple I suspect this isn'.t completely right, but it works well so far. 5 Search the distribution for an appropriate R and V.  Arguments:  Number of bins F target function (one-sided antitone PDF, not necessarily normalized)  function inverse * function definite integral (from 0 to _) G estimate of total volume under function (integral from 0 to infinity) Result: (R,V) z{|}~z{|}~z {|}~{|}~7A specification of a normal distribution over the type a.  Normal m s$ is a normal distribution with mean m and stddev sd. The "standard"( normal distribution - mean 0, stddev 1 6A random variable that produces a pair of independent  normally-distributed values. 6A random variable that produces a pair of independent D normally-distributed values, computed using the Box-Muller method. - This algorithm is slightly slower than Knuth's method but using a " constant amount of entropy (Knuth'!s method is a rejection method). ( It is also slightly more general (Knuth's method require an   instance). 6A random variable that produces a pair of independent 2 normally-distributed values, computed using Knuth's polar method.  Slightly faster than  when it accepts on the ' first try, but does not always do so. SDraw from the tail of a normal distribution (the region beyond the provided value)  Construct a {z+ for sampling a normal distribution, given   logBase 2 c and the  implementation. GZiggurat target function (upper half of a non-normalized gaussian PDF)  inverse of   integral of   volume of  AA random variable sampling from the standard normal distribution  over any 0 type (subject to the rest of the constraints -  it builds and uses a {z internally, which requires the   class). Because it computes a {z", it is very expensive to use for G just one evaluation, or even for multiple evaluations if not used and H reused monomorphically (to enable the ziggurat table to be let-floated  out). If you don'3t know whether your use case fits this description  then you'<re probably better off using a different algorithm, such as   or . And of course if  you don'6t need the full generality of this definition then you're much  better off using  or . @As far as I know, this should be safe to use in any monomorphic  Distribution Normal instance declaration. AA random variable sampling from the standard normal distribution  over the  type. AA random variable sampling from the standard normal distribution  over the  type.     ( is a normal variable with distribution . ' is a normal process with distribution .  normal m s( is a random variable with distribution  m s.  normalT m s' is a random process with distribution  m s.  derived from Marsaglia & Tang, /A Simple Method for generating gamma variablesL, ACM Transactions on Mathematical Software, Vol 26, No 3 (2000), p363-372.  *%'23456789:;<=>?@ABCDEFTUVW^_`a*54678;<=9:>?@ABEFTUCDVW'%23^_`a1The rayleigh distribution with a specified mode ("sigma" ) parameter.  Its mean will be  sigma*sqrt(pi,2)@ and its variance will be @sigma^2*(4-pi)2 2(therefore if you want one with a particular mean m, sigma should be m*sqrt(2/pi)) FA description of a triangular distribution - a distribution whose PDF E is a triangle ramping up from a lower bound to a specified midpoint G and back down to the upper bound. This is a very simple distribution E that does not generally occur naturally but is used sometimes as an G estimate of a true distribution when only the range of the values and 9 an approximate mode of the true distribution are known. _The lower bound of the triangle in the PDF (the smallest number the distribution can generate) AThe midpoint of the triangle (also the mode of the distribution) WThe upper bound of the triangle (and the largest number the distribution can generate) (Compute a triangular distribution for a   type. triangularCDF a b c is the CDF of realFloatTriangular a b c. !"#!"$!"%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJK L M L N O PQRS T T U V W X Y Z [ \ ] ^_`abcddeefghijklmnopqrstuvwxyyz{|}~  U            !"#$%&'()*+,-./012345678random-fu-0.1.3Data.Random.Source.PureMTData.Random.Internal.FindData.Random.Internal.FixedData.Random.Internal.WordsData.Random.Internal.THData.Random.LiftData.Random.Internal.PrimitivesData.Random.SourceData.Random.Source.DevRandomData.Random.Source.StdGenData.Random.Source.StdData.Random.RVarData.Random.DistributionData.Random.Sample Data.Random.Distribution.Uniform Data.Random.Distribution.WeibullData.Random.List"Data.Random.Distribution.Bernoulli$Data.Random.Distribution.Categorical$Data.Random.Distribution.Exponential!Data.Random.Distribution.ZigguratData.Random.Distribution.NormalData.Random.Distribution.GammaData.Random.Distribution.Beta!Data.Random.Distribution.Binomial$Data.Random.Distribution.Multinomial"Data.Random.Distribution.Dirichlet Data.Random.Distribution.Poisson!Data.Random.Distribution.Rayleigh#Data.Random.Distribution.TriangularData.Random.Source.MWC Data.Randommersenne-random-pure64-0.2.0.3System.Random.Mersenne.Pure64 newPureMTpureMTPureMTfindMaxfindMin findMinFrom resolutionOf resolutionOf2mkFixed unMkFixed buildWord16 buildWord32 buildWord32' buildWord64 buildWord64' buildWord64'' word32ToFloatword32ToFloatWithExcess wordToFloatwordToFloatWithExcess wordToDoubleword32ToDoublewordToDoubleWithExcess integralTypesrealFloatTypesreplicateInstancesLiftliftPrimPrimNByteInteger PrimDouble PrimWord64 PrimWord32 PrimWord16 PrimWord8 getPrimWheredecomposePrimWhere RandomSourcegetRandomPrimFrom MonadRandom getRandomPrim DevRandom DevURandomgetRandomPrimFromStdGenIOgetRandomPrimFromRandomGenRefgetRandomPrimFromRandomGenStategetRandomPrimBygetRandomPrimFromMTRefgetRandomPrimFromMTState StdRandomRVarTRVarrunRVarrunRVarT runRVarTWithCDFcdf DistributionrvarrvarT Sampleable sampleFromsample sampleState sampleStateT StdUniformUniformintegralUniformboundedStdUniformboundedEnumStdUniformfloatStdUniformdoubleStdUniformrealFloatStdUniformfixedStdUniformrealStdUniformCDF floatUniform doubleUniformrealFloatUniform fixedUniformrealUniformCDFuniformuniformT stdUniform stdUniformT stdUniformPosstdUniformPosTWeibull weibullLambdaweibullK randomElementshuffleshuffleN shuffleNofM Bernoulli bernoulli bernoulliT boolBernoulliboolBernoulliCDFgeneralBernoulligeneralBernoulliCDF Categorical categorical categoricalTweightedCategorical empiricalmapCategoricalPsnormalizeCategoricalPs collectEventscollectEventsBy ExponentialExpfloatingExponentialfloatingExponentialCDF exponential exponentialTZiggurat zTable_xszTable_y_ratios zTable_yszGetIU zTailDistzUniformzFunczMirror runZiggurat mkZiggurat_ mkZiggurat mkZigguratRecfindBin0Normal StdNormal normalPairboxMullerNormalPairknuthPolarNormalPair normalTailrealFloatStdNormaldoubleStdNormalfloatStdNormal stdNormal stdNormalTnormalnormalTErlangGammamtGammagammagammaTerlangerlangTBetafractionalBetabetabetaTBinomialintegralBinomialintegralBinomialCDFfloatingBinomialfloatingBinomialCDFbinomial binomialT Multinomial multinomial multinomialT DirichletfractionalDirichlet dirichlet dirichletTPoissonintegralPoissonintegralPoissonCDFfractionalPoissonfractionalPoissonCDFpoissonpoissonTRayleighfloatingRayleighrayleigh rayleighT rayleighCDF TriangulartriLowertriMidtriUpperfloatingTriangular triangularCDFbaseGHC.RealRational Data.FixedFixed integer-gmpGHC.Integer.TypeInteger Unsafe.Coerce unsafeCoerceGHC.WordWord32ghc-prim GHC.TypesFloatDoubleWord64Integral GHC.Float RealFloat replaceNametemplate-haskellLanguage.Haskell.TH.SyntaxDecNametransformers-0.2.2.0Control.Monad.Trans.Class MonadTrans$fLiftIdentitymMonadPrompt-1.0.0.2Control.Monad.PromptPrompt devRandom devURandomdevrandom-1.0.0.2 System.Random RandomGenStdGen GHC.IORefIORefIOControl.Monad.Trans.State.LazyStateunRVarTData.Functor.IdentityIdentityGHC.EnumEnumBounded FractionalintegralUniform'integralUniformCDF bytesNeeded powersOf256minBoundmaxBoundboundedStdUniformCDFboundedEnumStdUniformCDF enumUniformenumUniformCDFstdUniformNonnegGHC.BoolTrueFalseGHC.BasefmapmkTail zigguratTablezigguratExcess zigguratXsprecomputeRatios GHC.ClassesOrdnormalZnormalF normalFInv normalFInt normalFVol erf-1.0.0.0Data.Number.ErfErfdoubleStdNormalCdoubleStdNormalRdoubleStdNormalVdoubleStdNormalZfloatStdNormalCfloatStdNormalRfloatStdNormalVfloatStdNormalZ normalCdfFloating