Search code examples
c#randomweighted

Weighted random number generation C#


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);

Solution

  • 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.