Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random double C++11

The code below show how to random double in C++11. In this solution each time, when I run this program the result are the same - I don't know why? How to change it to get different solution in every time when I run the program?

#include <random>
int main(int argc, char **argv)
{
  double lower_bound = 0.;
  double upper_bound = 1.;
  std::uniform_real_distribution<double> unif(lower_bound, upper_bound);
  std::default_random_engine re;      
  double a_random_double = unif(re);
  cout << a_random_double << endl;
  return 0;
}
//compilation: "g++ -std=c++0x program_name.cpp -o program_name"
like image 582
user1519221 Avatar asked Jan 13 '14 21:01

user1519221


2 Answers

You need to seed the random number generator before you generate samples. You do this when you construct the default_random_engine instance. For example:

std::random_device rd;
std::default_random_engine re(rd()); 

If you wish to be more prescriptive about the generator you use then you should specify one rather than relying on the library implementor's choice for default_random_engine. The available choices are listed here: http://en.cppreference.com/w/cpp/numeric/random#Predefined_random_number_generators

Also beware that some implementations do not use a non-deterministic source for random_device. If you are faced with such an implementation, you'll need to find an alternative source for your seed.

like image 166
David Heffernan Avatar answered Sep 29 '22 11:09

David Heffernan


You have to initialize the random engine with some initial seed value.
An option is to use std::random_device.

#include <iostream>
#include <random>

int main() {
    const double lower_bound = 0;
    const double upper_bound = 1;
    std::uniform_real_distribution<double> unif(lower_bound, upper_bound);
    
    std::random_device rand_dev;          // Use random_device to get a random seed.

    std::mt19937 rand_engine(rand_dev()); // mt19937 is a good pseudo-random number 
                                          // generator.

    double x = unif(rand_engine);
    std::cout << x << std::endl;
}

You may want to watch a great presentation freely available online: "rand() Considered Harmful" (from GoingNative 2013 C++ event).

like image 39
Mr.C64 Avatar answered Sep 29 '22 11:09

Mr.C64