Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid same sequences of random numbers

I would like to generate different sequences of uniformly distributed samples. To this end, I initialize the default random engine with different seeds, but the same sequences are produced:

#include <iostream>
#include <random>

void fun(double seed)
{
    std::cout << "given seed: " << seed << std::endl;
    std::default_random_engine gen_2(seed);
    std::uniform_real_distribution<double> dis_2(0.0,1.0);
    std::cout << dis_2(gen_2) << std::endl;
    std::cout << dis_2(gen_2) << std::endl;
}

int main()
{
    double seed = 1.0;
    std::default_random_engine gen_1(seed);
    std::uniform_real_distribution<double> dis_1(0.0,1.0);
    for(size_t i=0; i<3; ++i)
    {
        fun(dis_1(gen_1));
    }
}

The output reads:

given seed: 0.0850324

0.0850324

0.891611

given seed: 0.891611

0.0850324

0.891611

given seed: 0.18969

0.0850324

0.891611

How can I produce different sequences in the function fun?

like image 855
PolarBear Avatar asked Jul 20 '20 09:07

PolarBear


People also ask

How do you generate unique random numbers?

In a column, use =RAND() formula to generate a set of random numbers between 0 and 1.

Can you generate the same random numbers everytime?

random seed() example to generate the same random number every time. If you want to generate the same number every time, you need to pass the same seed value before calling any other random module function.

How do I restrict math random?

random() method what generates a floating point random number from 0 to 1. In order to restrict it, you need to do something like this: var low:Number = 1; var high:Number= 100; var result:Number = Math.

Why is 17 the most common random number?

Seventeen is: Described at MIT as 'the least random number', according to the Jargon File. This is supposedly because in a study where respondents were asked to choose a random number from 1 to 20, 17 was the most common choice. This study has been repeated a number of times.


1 Answers

The seed of the generator is an integer.

The problem is that all numbers generated by your dis_1 are less than 1, and greater than or equal to 0. Therefore they implicitly convert to the same value 0 when converted to an integer.

The solution is to use a different seed, rather than 0 always.

like image 72
eerorika Avatar answered Sep 29 '22 12:09

eerorika