Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Implementing simple binary probability distribution.

Posted on 2000-04-24
4
Medium Priority
?
337 Views
Last Modified: 2010-04-15
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.
0
Comment
Question by:mm162
  • 2
4 Comments
 
LVL 1

Accepted Solution

by:
snifong earned 100 total points
ID: 2745074
int p = 40; // probability for 0
int q = 1 - p; // 1 - probability for 1
srand() = time(NULL);
for loop here with counter i...
if (rand() % 100 <= p)
   Array[i] = 0;
else
   Array[i] = 1;
end for loop
0
 
LVL 22

Expert Comment

by:cookre
ID: 2745089
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;




0
 
LVL 85

Expert Comment

by:ozo
ID: 2745090
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
0
 
LVL 22

Expert Comment

by:cookre
ID: 2745312
'struth ozo, but how many folks browse locked questions?  I know I don't.  I suppose I ought to start...
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
Suggested Courses

885 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question