1

I have been trying to search answer for this, but all discussions that I have found are either in language that I don't understand or relies on having a collection where each element has its own weight.

I want to basically just get a random number between 0 and 10, which is "middle-weighted" as in 5 comes more often than 0 and 10. Basically I have been trying to figure out an algorithm where I can give any number to be the "weighted number" between min and max values that I have defined and all the numbers generated would be weighted appropiately. I know that this may sound like "I dont want to think about this, I'll just sit back and wait someone else to do this", but I have been thinking and searching about this for like an hour and I'm really lost :|

So in the end, I want that I could call ( via extension method )

random.NextWeighted(MIN, MAX, WEIGHT); 
3
  • 1
    What would the weight be? How much more frequently? Do you want a normal distribution? Commented Oct 3, 2011 at 21:43
  • 1
    Let's first assume that you want the numbers zero through nine, so there are ten possibilities. If you drew a histogram of a million runs of the regular RNG, you'd expect to get a hundred thousand hits in each column of the histogram. Can you describe what your desired histogram looks like in detail? Commented Oct 3, 2011 at 22:25
  • You'll have to figure out the desired probability distribution first. Commented Oct 4, 2011 at 3:06

2 Answers 2

4

You have an inverse normal distribution method available.

  1. Scale your random number so that it's a double between zero and one.

  2. Pass it to InverseNormalDistribution.

  3. Scale the returned value based on the weight. (For example, divide by weight over 100.)

  4. Calculate [ (MIN + MAX) / 2 ] + [ (ScaledValue) X (MAX - MIN) ]

  5. If that's less than MIN, return MIN. If it's more than MAX, return MAX. Otherwise, return this value.

Sign up to request clarification or add additional context in comments.

Comments

3

I don't know how much more often you want 5 to appear than the other numbers between 0-10 but you could create an array with the distribution you want.

Something like

var dist = new []{0,1,2,3,4,5,6,7,8,9,10,5,5,5}; 

Then you get a random positions of 0 and 13 you will get numbers between 0-10 but a 5 four times more often than the others. Pretty fast but not very practical if you want numbers between 0 and billion though.

1 Comment

So simple yet effective!