Solved

Implementing simple binary probability distribution.

Posted on 2000-04-24
4
298 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 50 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 84

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

ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

Question has a verified solution.

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

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

929 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now