Ranges and random numbers -- again

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Tue Jun 18 04:42:19 PDT 2013


On 06/18/2013 12:09 PM, Joseph Rushton Wakeling wrote:
> ... we get different sequences.  However, the .save as implemented needs
> rewriting (I haven't touched it yet) as currently it simply returns a reference
> copy.  I'll get onto that. :-)

Tweaked version attached.  This adds a new constructor which copies a PRNG of
the same type:

    this(typeof(this) source)
    {
        this.mt[] = source.mt[];
        this.mti = source.mti;
        this._y = source._y;
    }

... and .save then makes use of this to return a duplicate:

    @property typeof(this) save()
    {
        return new typeof(this)(this);
    }

With this in hand, we can do,

    auto gen = new MtClass19937(unpredictableSeed);

    auto t1 = gen.take(5);
    auto t2 = gen.take(5);
    writeln(t1);
    writeln(t2);

... and get two independent sequences, whereas,

    auto t3 = gen.take(5);
    auto t4 = gen.save.take(5);
    writeln(t3);
    writeln(t4);

... produces two identical sequences.

This still requires some intelligence/virtue on behalf of the programmer,
though: if we do,

    auto t5 = gen.save.take(5);
    writeln(t5);

... and don't also take 5 from gen itself, then subsequent uses of gen will be
correlated with t5, probably unintentionally.  However, I think that's a fair
tradeoff for the ability to .save at all.

It's also now trivial to rewrite things like my SimpleRandomRange such that,

    auto gen = new MtClass19937(unpredictableSeed);
    auto r = simpleRandomRange(0.0L, 1.0L, gen);

    auto t1 = r5.take(5);
    auto t2 = r5.take(5);
    writeln(t1);
    writeln(t2);

... produces different sequences, whereas,

    auto t3 = r5.take(5);
    auto t4 = r5.save.take(5);
    writeln(t3);
    writeln(t4);

... produce the same.  Ditto for "real" random ranges, such as
std.random.RandomSample.

So we have a solution to the first set of problems identified, that is much
nicer than the one I had in mind.  Very good!

However, at least one more niggle remains -- to be followed up on.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: mtclass.d
Type: text/x-dsrc
Size: 5624 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20130618/6fe2f52e/attachment.d>


More information about the Digitalmars-d mailing list