Re: Is there a better way to simulate randomly choosing from a weighted set?
- From: "Russell Easterly" <logiclab@xxxxxxxxxxx>
- Date: Mon, 27 Feb 2006 16:43:21 -0800
<yay_frogs@xxxxxxxxx> wrote in message
news:1141032840.306704.88070@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[I originally posted this to comp.lang.c++ since that is the language<snip>
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.
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
.
- References:
- Prev by Date: Re: Is there a better way to simulate randomly choosing from a weighted set?
- Next by Date: Re: Is there a better way to simulate randomly choosing from a weighted set?
- Previous by thread: Re: Is there a better way to simulate randomly choosing from a weighted set?
- Next by thread: Re: Is there a better way to simulate randomly choosing from a weighted set?
- Index(es):
Relevant Pages
|