Search code examples
randomarmadillo

Armadillo generates the same random numbers


I generate a matrix with randoms using Armadillo package (v.7.300.1) under cygwin64 (or minGW):

#include<armadillo>

int main(){
  arma::mat(3,3, arma::fill::randu).print();
  return 0;
}

The program (after re-build or re-run) always generates:

0.6900  0.5548  0.2074    
0.5054  0.3784  0.6263    
0.5915  0.2577  0.3401

Why is it always the same? What's wrong?


Solution

  • You forgot to set the seed to introduce randomness. Recall that all (Q)RNGs are deterministic. What you see here, Conrad would call a feature.

    From the docs:

    To change the RNG seed, use arma_rng::set_seed(value) or arma_rng::set_seed_random() functions.

    Demo

    A slightly repaired version of your file:

    /tmp$ cat armaRand.cpp 
    #include<armadillo>
    
    int main(){
      arma::arma_rng::set_seed_random();
      arma::mat(3,3, arma::fill::randu).print();
      exit(0);
    }
    /tmp$ g++ -o armaRand armaRand.cpp 
    /tmp$ ./armaRand 
       0.8824   0.4457   0.3589
       0.7134   0.4768   0.8335
       0.0171   0.4119   0.3720
    /tmp$ ./armaRand 
       0.3417   0.3643   0.6865
       0.2814   0.0191   0.6797
       0.9737   0.1593   0.5013
    /tmp$ 
    

    If you want reproducible results you want to use the other variant and keep track of the seed value.

    Edit: In late 2018 with newer version of Armadillo, linking appears now to be required so please make it g++ -o armaRand armaRand.cpp -larmadillo. The rest still holds: by seeding the random number generator with (sufficiently) random bits we do get different answers as expected.