Link to home
Start Free TrialLog in
Avatar of mm162
mm162

asked on

Implementing simple binary probability distribution.

Using C/C++, I would like the computer to randomly fill some array with either 0s or 1s, in some proportion p.  That is, let Array be some n dimensional array.  Then, for every i, I want Array[i] = 0 with probability p and = 1 with probability 1-p.
ASKER CERTIFIED SOLUTION
Avatar of snifong
snifong
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Assuming you have the function 'rand()' that returns an int x, 0<=x<=RAND_MAX, and given probability float p, 0<=p<=1, then:

1) For a given p, compute
int CutPoint;
CutPoint=(int) (.5+p*(float)RANDMAX);

2) For any i, compute
if   (rand()>=CutPoint) Array[i]=1;
else                    Array[i]=0;




Avatar of ozo
int p = 40; // probability for 0
Probabilities are never greater than 1

int q = 1 - p; // 1 - probability for 1
Nor can probabilities be negative
'struth ozo, but how many folks browse locked questions?  I know I don't.  I suppose I ought to start...