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

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

With weight == 0 the result will be equal to the minimum, and with weight == 1 the result will be equal to the maximum. With a weight of == 0.5, all numbers within the range will have an equal chance of choice.

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

+4
source share
3 answers

I have a short tutorial describing how to do this:

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

:

  • , , .
  • .
  • , .
  • . , .
  • .
+15

[0, 1]:

Random rnd = new Random();
double weight = ...; // must be in [0, 1];

double r = rnd.NextDouble();
if (weight < 0.5)
    val = 1 - Math.Pow(r, weight * 2);
else
    val = Math.Pow(r, (1 - weight) * 2);

[min, max]

double val2 = val * (max - min) + min;
0

-, , .

, , 0 1 $w $ 0 1. : $\ alpha $ $\ beta $. $\ alpha = 2 * w $ $\ beta = -wlog_2 (w) - (1-w) * log_2 (1-2) $( . 0 1, 0,5 . - , , .

0

Source: https://habr.com/ru/post/1649589/


All Articles