Re: Is there a better way to simulate randomly choosing from a weighted set?




<yay_frogs@xxxxxxxxx> wrote in message
news:1141032840.306704.88070@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[I originally posted this to comp.lang.c++ since that is the language
I'm working in, but then I realized that my problem isn't language
specific and this would probably be a better group.]

Here is my problem: suppose there are, say, five events with these
probabilities:

event1 0.7
event2 0.1
event3 0.1
event4 0.05
event5 0.05

Note that sum of the probabilities is 1.0. I would like a function that
simulates these events and returns an int to indicate which event
occurred: the function should statistically return 1 about 70% of the
time, 2 about 10% of the time, and so on.

<snip>
So is there a better way?

There is a simpler way.
Have an array with your probabilities in it.
Generate a random real number, x, between 0 and 1.
Loop through and add up your probabilities until you get a number >= x.
This works if your probabilities are normalized to 1.

If x <= .7 return 1.
If x <= .8 (.7+.1) return 2.
If x <= .9 (.8+.1) return 3.
etc.

This won't be very efficient if you have a lot of probabilities.


Russell
- 2 many 2 count


.



Relevant Pages

  • Re: Phaistos Disk : the DOGMATICS and the PROOFS (Was: The Phaistos Disk, side A, according to...)
    ... > grapheus wrote: ... > The identity of the language is not known. ... > form of Greek, and choose sign-values to make it come out as Greek, then ... UNABLE TO DEAL WITH PROBABILITIES!... ...
    (sci.lang)
  • Re: Practical Common Lisp gets practical
    ... I realize that I may have used some language ... Why don't you just take the logarithm of all ... (log (reduce #'* probs)) ... If you need to guard against some of the probabilities being zero, ...
    (comp.lang.lisp)
  • Re: First Program
    ... an array. ... I am just beginning to learn this language. ... int total = 0; ... good,) but not in a similar loop in add_array. ...
    (comp.lang.c)
  • Re: Improved for each loop
    ... Objectarray .... ... Saving a little bit of typing is not worth changing the language for. ... A lot of people are used to 3 argument for loop - not just in Java ...
    (comp.lang.java.programmer)
  • Re: First Program
    ... an array. ... I am just beginning to learn this language. ... int total = 0; ... good,) but not in a similar loop in add_array. ...
    (comp.lang.c)