# random number generation

Discussion in 'C Programming' started by Bo Sun, Jun 12, 2004.

1. ### Bo SunGuest

hi,

I would like to code the following problem:

there are 4 events, and their happening probability is:

e1 with probability 0.5
e2 with probability 0.2
e3 with probability 0.2
e4 with probability 0.1

I want to use some random function generation function. when its return
value is [0. 0.5), I select e1, when it is [0.5, 0.75), I select e2..

My question is: which function should I use to generate [0, 0.5).. based
on the probability? How should I code this?

Many thanks,

Bo

Bo Sun, Jun 12, 2004

2. ### NudgeGuest

Bo Sun wrote:

> I would like to code the following problem:
>
> there are 4 events, and their happening probability is:
>
> e1 with probability 0.5
> e2 with probability 0.2
> e3 with probability 0.2
> e4 with probability 0.1
>
> I want to use some random function generation function. when its return
> value is [0. 0.5), I select e1, when it is [0.5, 0.75), I select e2..
>
> My question is: which function should I use to generate [0, 0.5).. based
> on the probability? How should I code this?

#include <stdlib.h>

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

if (p < 0.5) return e1;
if (p < 0.7) return e2;
if (p < 0.9) return e3;
else return e4;

Nudge, Jun 12, 2004