Przejdź do głównej zawartości

Posty

Wyświetlanie postów z grudzień, 2016

C++11 random - introduction

C++11 introduced robust random numbers library, <random>. Its author does great introduction in the video from Cppcon:
I will attempt to create short tutorial/HOWTO for this library.
Bad, old times Before C++11, when you wanted to get random numbers in range {1, 2, ... 10}, you wrote something like this:
#include <stdio.h>      /* printf, NULL */ #include <stdlib.h>     /* srand, rand */ #include <time.h>       /* time */ int main () { srand (time(NULL)); int num1 = rand()%10 + 1; int num2 = rand()%10 + 1; return 0; } Several things are wrong here:
It always gives uniform distribution (1 is as probable as 5). This is usually fine, but when not, you need a lot of additional work.Actually, it is not very uniform.If you want for some reason to reseed the generator (call srand(time(NULL)) again) shortly after first seeding, you may get repeated answersYou only get discreet numbers (integers)Random algorithm is not specified, so results are not portab…