Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++, how randomly with given probabilities choose numbers

Tags:

c++

math

I have N numbers n_1, n_2, ...n_N and associated probabilities p_1, p_2, ..., p_N. function should return number n_i with probability p_i, where i =1, ..., N. How model it in c++?
I know it is not a hard problem. But I am new to c++, want to know what function will you use. Will you generate uniform random number between 0 and 1 like this:

((double) rand() / (RAND_MAX+1))
like image 909
ashim Avatar asked Dec 27 '11 07:12

ashim


1 Answers

This is very similar to the answer I gave for this question:

changing probability of getting a random number

You can do it like this:

double val = (double)rand() / RAND_MAX;

int random;
if (val < p_1)
    random = n_1;
else if (val < p_1 + p_2)
    random = n_2;
else if (val < p_1 + p_2 + p_3)
    random = n_3;
else
    random = n_4;

Of course, this approach only makes sense if p_1 + p_2 + p_3 + p_4 == 1.0.

This can easily be generalized to a variable number of outputs and probabilities with a couple of arrays and a simple loop.

like image 149
Mysticial Avatar answered Sep 30 '22 00:09

Mysticial