0

What is the easiest way to get a Bernoulli distributed random variable in C++? I I have a non-const p. p starts from 0, getting p+=0.01 , until p=1. ("for" loop) I have this idea:

declare int aray in size of 100, intilized with zeros. evrey time the p gets +0.01, I change one zero to "1"... and get a random number%100.

is it good? thanks

Gabriel Moretti
  • 676
  • 8
  • 23
Atheel
  • 187
  • 1
  • 3
  • 16

2 Answers2

4

You should use modern C++ (C++11 or later if possible). You can do this:

#include <random>
#include <iostream>

int main()
{
    std::random_device rd{}; // use to seed the rng 
    std::mt19937 rng{rd()}; // rng

    double p = 0.2; // probability
    std::bernoulli_distribution d(p);

    // generate 5 runs
    for(std::size_t i = 0; i < 5; ++i)
        std::cout << d(rng) << " ";
}
vsoftco
  • 55,410
  • 12
  • 139
  • 252
3

you can get a random number between 0 and 1, and calculate the bernoulli random number from it

double p = 0.5;
double r = ((double) rand() / (RAND_MAX));
unsigned int br = 0;
if (r >= p) 
   br = 1;
dlavila
  • 1,204
  • 11
  • 25