Paul <
peps...@gmail.com> writes:
[edited and rearranged]
> The following code is designed to randomly (and uniformly) pick a
> number between 0 and 1.
>
> // Uniform distribution between 0 and 1.
> // Seed is reset by incrementing the seed randomly each time the
> // function is called.
> double RandomGen::nextDouble()
> {
> static long long seedCounter = 0;
> std::default_random_engine generator;
> generator.seed(seedCounter);
>
> seedCounter += rand();
> /* The simpler ++seedCounter does not work.
> It leads to relative errors that are too small to be credible. */
>
> std::uniform_real_distribution<double> distribution(0.0, 1.0);
> return (distribution(generator));
> }
>
> It received a complaint that the seed shouldn't be reset each
> time. However, if you don't do that, then you just get exactly
> the same result each time nextDouble() is called.
>
> Can anyone make any sense of this complaint? [...]
Generally it's not a good idea to use setting a seed value to get
another random number. The usual advice is seed once, then
extract as many random numbers as you need.
I realize that what you're doing here follows a different
pattern. However it's still not a good idea. The size of the
state space may be greatly reduced. The quality of the
generated seeds may be low (rand() is notoriously unreliable).
And random number generators sometimes take an iteration or
several to "get up to speed" after being seeded.
If it were me I might do something along these lines (please
excuse changes in naming):
class RandomGenerator {
static std::default_random_engine uniform_double_generator;
public:
static double uniform_double();
static void seed_uniform_double( unsigned long long s ){
uniform_double_generator.seed( s );
}
};
std::default_random_engine RandomGenerator::uniform_double_generator;
double
RandomGenerator::uniform_double(){
std::uniform_real_distribution<double> distribution(0.0, 1.0);
return distribution( uniform_double_generator );
}
I added an interface to seed the underlying generator, and
avoided any call to rand(). Usually it's a good idea not
to couple different generators, so numbers used for one
purpose don't interfere with another. The key point though
is to use the underlying generator, and not rely on seeding
to give the randomness.