MathGroup Archive 2003

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

Search the Archive

Re: discrete frequency distribution

  • To: mathgroup at smc.vnet.net
  • Subject: [mg43450] Re: discrete frequency distribution
  • From: mdw at ccu1.auckland.ac.nz (Michael Woodhams)
  • Date: Wed, 17 Sep 2003 07:59:13 -0400 (EDT)
  • References: <bhaa1e$kkr$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Jan Schmedes <schmedes at rz.uni-potsdam.de> wrote in message news:<bhaa1e$kkr$1 at smc.vnet.net>...
> dear group,
> 
> i have a set of points which describe a varaible and his frequency, e.g.
> counting the age of N people in "age-bins" 0-10 a,10-20 a,20-30 a,... .
> Given this discrete frequency distribution i want to produce random
> numbers.
> How could i do this?
> 
> Thank you for help
> 
> Jan Schmedes

I only found this thread because I was searching the group for the
answer to the same question, so sorry that this is a bit late.

Here is my solution:

discreteRandom[c_List] := With[{r = Random[]},
      Position[c, x : _ /; x > r, 1, 1]
];
discreteRandomN[c_List, n_Integer /; n > 0] := Module[{counts},
      counts = Table[0, {Length[c]}];
      Map[counts[[#]]++ &, Flatten[Table[discreteRandom[c],{n}]]]; 
      Return[counts];
];

and called as like so, where the vector is the cumulative distribution
function:

In[314]:=discreteRandomN[{0.1, 0.3, 0.6, 1.0}, 10000]
Out[314]:={1033, 2010, 2996, 3961}

As written, discreteRandom annoyingly returns something like "{{2}}"
instead of "2". This doesn't bother me, as I only intend to access it
through discreteRandomN, not directly, but if you prefer to remove
this wart:

discreteRandom[c_List] := With[{r = Random[]},
      Position[c, x : _ /; x > r, 1, 1][[1]][[1]]
];
discreteRandomN[c_List, n_Integer /; n > 0] := Module[{counts},
      counts = Table[0, {Length[c]}];
      Map[counts[[#]]++ &, Table[discreteRandom[c],{n}]]; 
      Return[counts];
];

If you have a the non-cumulative frequencies (i.e. "{0.1,0.2,0.3,0.4}"
in the above example) you can convert with:
cumulative = Table[Sum[nonCumulative[[j]], {j, 1, i}], {i, 1,
Length[nonCumulative]}];

Comments on efficiency and style are welcome - I haven't been at this
for long. (Yes, I know I could say "counts" instead of
"Return[counts];" but I prefer an explicit return from any
multi-statement function.)

If you want to send me e-mail, I am currently at massey.ac.nz,
username M.D.Woodhams.

-- Quattour res in hoc mundo sanctae sunt: libri, liberi, libertas et
liberalitas.


  • Prev by Date: Re: Finding the Path to/Directory for the current EvaluationNotebook?
  • Next by Date: Re: randomly chosen parameters fails NDSolvewith a large ode system
  • Previous by thread: Nonzero Min[]
  • Next by thread: Re: randomly chosen parameters fails NDSolvewith a large ode system