On Sun, 07 Oct 2018 09:18:27 -0700, Paul wrote:
> I understand from a previous thread (and thanks to everyone who answered
> there)
> that the seed of a random number generator should be kept constant
> throughout the running of the program.
> The below is a bugged program which tries (but fails) to generate a
> random uniform number between 0 and 1.
>
> I am aware of good solutions to the problem by others, and have been
> successful myself. However, the below code has a bug and I don't
> understand why. It responds by choosing the same number each time it is
> called.
Which number ?
[Code in question:]
> double RandomGen::nextDouble() const {
> static std::default_random_engine generator(0);
> static std::uniform_real_distribution<double> distribution(0.0,
> 1.0);
> return (distribution(generator));
> }
How did you test this code? When I write a little test code like
#include <random>
#include <iostream>
double rand_double ( void ) {
static std::default_random_engine generator ( 0 );
static std::uniform_real_distribution<double> distribution ( 0.0,
1.0 );
return ( distribution( generator ) );
}
int main ( void ) {
for ( int i = 0; i < 10; ++ i ) {
std::cout << rand_double() << "\n";
}
}
I get:
0.131538
0.45865
0.218959
0.678865
0.934693
0.519416
0.0345721
0.5297
0.00769819
0.0668422
That looks pretty much random and between 0 and 1.
Best,
Kai-Uwe Bux