random number generation

B

Bo Sun

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
 
N

Nudge

Bo said:
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;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top