MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: easy question about random numbers

  • To: mathgroup at smc.vnet.net
  • Subject: [mg53424] Re: easy question about random numbers
  • From: Mark Fisher <mark at markfisher.net>
  • Date: Tue, 11 Jan 2005 01:31:12 -0500 (EST)
  • References: <crqb7f$cak$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Here's a faster version (again using Piecewise) that incorporates the 
calls to Random[] into the compiled function:

MakeDiscreteRandomFunction[probs_, vals_] :=
   With[{
     fun = Block[{x},
       Function @@ {x, Piecewise @
         Transpose[{vals,
           x <= # & /@ (Rest @ FoldList[Plus, 0, probs])}]}
         ]},
       Compile[{{n, _Integer}},
         fun /@ Table[Random[], {n}]
         ]
     ]

MakeDiscreteRandomFunction[probs_] :=
   MakeDiscreteRandomFunction[probs, Range[Length[probs]]]

li2= {1/6, 1/6, 1/6, 1/6, 9/60, 11/60}
ranfun = MakeDiscreteRandomFunction[li2]

ranfun[10]

--Mark

Pedrito wrote:

> Hi everybody!
> 
> I wanted to obtain a discrete random number generator that I needed for
> a project.
> 
> On the library Statistics`DiscreteDistributions` I could find the DiscreteUniformDistribution
> function. But I wanted to specify the probability for each one of the
> states.
> 
> 
> For instance:
> If we need to simulate an unfair dice, we could have this probabilities
> for each one of the sides:
> {1/6, 1/6, 1/6, 1/6, 9/60, 11/60}
> 
> So I wrote:
> li2 = {1/6, 1/6, 1/6, 1/6, 9/60, 11/60}
> li3=FoldList[Plus,0,li2]
> Module[{i = 1, r = Random[]}, While[ !li3[[i]] < r < li3[[i + 1]], i++]; i]
> 
> It works ok but I don't know if there is another (better) way of doing
> this.
> Any suggestion?
> 


  • Prev by Date: Re: easy question about random numbers
  • Next by Date: Re: easy question about random numbers
  • Previous by thread: Re: easy question about random numbers
  • Next by thread: Re: Re: easy question about random numbers