Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a random number generator with a weight in C#? [closed]

I am trying to write a random number generator function in C# that would take a minimum, maximum, and weight parameters.

With weight == 0, the result would equal minimum, and with weight == 1, the result would equal maximum. With weight == 0.5, all the numbers within the range would have equal chance of being selected.

What I want to achieve is as the weight is approaching the minimum, the minimum has more chances of being selected and the maximum less, and vice versa.

like image 564
tau-badger Avatar asked Dec 06 '22 17:12

tau-badger


1 Answers

I have a short tutorial describing how to do that here:

https://ericlippert.com/2012/02/21/generating-random-non-uniform-data/

Summary:

  • State the function parameterized by your weighting parameter that gives the probability distribution function.
  • Use calculus to integrate that function to get the cumulative distribution function.
  • Invert that function to get the quantile function.
  • Implement the quantile function, and pass the output of a uniformly distributed random source into the quantile function. The result will be a random source that conforms to the desired distribution.
  • Transform that function onto your integer range, and round appropriately.
like image 126
Eric Lippert Avatar answered Jan 02 '23 04:01

Eric Lippert