I have to run a simulation where each event E_i has a certain probability P_i to happen (i=1..4, sum_i P_i = 1).
I would like to write a function that, taken as input the four different probabilities (they depend on other things happening in my simulation), returns the integer i for the chosen event.
Which is the best way to write such a function (possibly only using standard libraries,
I have to run it on a cluster where I don’t own the permissions to add new libraries)?.
I was thinking to write something like:
int get_event(double p1,double p2, double p3, double p4){
double r=((double) rand())/(RAND_MAX); // alternatively here there can be any function that
// generates a random number uniformly distribute in (0,1);
if (r<=p1) return 1;
else if (r>p1 && r <=(p1+p2)) return 2;
else if (r>(p1+p2) && r <=(p1+p2+p3)) return 3;
else if (r>(p1+p2+p3) && r <=1) return 4;
else return -1; // -1 is an en error code;
}
but I am not sure if this is the best approach. Any suggestion?
Thanks a lot in advance.
That’s pretty good, I’d suggest only a few small changes: