On Thursday, 14 June 2012 at 22:17:44 UTC, Jonathan M Davis wrote:
On Thursday, June 14, 2012 23:37:05 jerro wrote:
Issues with copying rngs are not unique to randomSample - anyone
who uses random number generators will run into them
sooner or later. So the problem is not that randomSample takes
a rng as a parameter - it's that rngs are value types. The
proper solution would be to make them reference types.

Exactly. This has been discussed before (IIRC, there's a bug report which discusses it). The most straightforward solution is to change the random number generator ranges to classes, but that _will_ break code, because
they're constructed completely differently.

I don't think the solution is to pass the RNGs as refs. I'm not familiar with the precise bug report you mention, but the reasoning is clear: it's because if you do something like,

    auto getRandomSample(size_t N, size_t n)
    {
        auto rng = Random(unpredictableSeed);
        auto sample = randomSample(iota(0, N), n, rng);
    }

    void main()
    {
        writeln(getRandomSample(100, 5));
    }

... then if the RNG were stored in RandomSample by ref rather than value, this will fail, because the variable rng will no longer exist when the sample is evaluated in main().

As far as I can see the only _safe_ option is that randomSample must always be passed a uniquely seeded RNG. And if you take that line then it's a small step to conclude that you can dispense with passing an RNG at all and just pass the seed, with the RNG type passed as a template parameter.

Reply via email to