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: [mg53399] Re: easy question about random numbers
  • From: Justin Kaeser <jast-news at zno.de>
  • Date: Sun, 9 Jan 2005 23:04:02 -0500 (EST)
  • References: <crqb7f$cak$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Pedrito wrote:

> 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?

I came up with this, which basically implements your idea in a different 
style:

DiscreteRandomFunction[p_List] :=
  Module[{intervals = FoldList[Plus, 0, p], r},
     (r = Random[]; Length[Select[intervals, # â?¤ r &]] - 1) &]

This creates a function which returns random numbers with the given 
distribution p. Usage:

drf = DiscreteRandomFunction[{1/6, 1/6, 1/6, 1/6, 9/60, 11/60}]
  to get the function
drf[]
  to get the numbers

It appears to be marginally faster than your version (ca 2% ;) but still 
by magnitudes slower than Random[]. I'd love to see a more effeicent 
algorithm.


  • Prev by Date: Re: 2D plot for lists?
  • Next by Date: Inverse polynomials
  • Previous by thread: Re: easy question about random numbers
  • Next by thread: Re: Function Show[]