Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# Implementing simple binary probability distribution.

Posted on 2000-04-24
Medium Priority
334 Views
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
Question by:mm162
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 1

Accepted Solution

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

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

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

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

Question has a verified solution.

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

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
###### Suggested Courses
Course of the Month8 days, 15 hours left to enroll