Solved

Implementing simple binary probability distribution.

Posted on 2000-04-24
4
291 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

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…
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…
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

746 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

10 Experts available now in Live!

Get 1:1 Help Now