C++Guns – RoboBlog

06.05.2020

C++ Guns: generate random bits - std C++ way

Filed under: Allgemein — Tags: — Thomas @ 05:05

I found only one std C++ way to generator random bool value: using std::bernoulli_distribution. It returns bool values and has a default constructor with probability p=0.5. So the generated boolen are "uniform" distributed.

This is perhaps the slowest variant. The internet is full of better ideas. Some use std C++ random classes but they all need some extra code to work. For example: cast int to bool, extract one bit from a 32bit integer value.

#include <random>

std::random_device rd;
std::mt19937 g(rd());
std::bernoulli_distribution dis_true_false;

if(dis_true_false(g)) {
   // heads
} else {
   // tails
}

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress