Range of n random numbers

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Sun Apr 22 17:13:04 PDT 2012


Related to my earlier question -- I was wondering if there's a trivial way of 
generating a range of n random numbers according to a given distribution and 
parameters.

I wrote up the code below to generate a range of n uniformly-distributed 
numbers, but am not sure how to generalize it for arbitrary distribution and/or 
parameters, and I'm also not sure that I'm overcomplicating what might be more 
easily achieved with existing D functionality.

///////////////////////////////////////////////////////////////////////////////
import std.array, std.random, std.range, std.stdio;

struct UniformRange(T1, T2)
{
       T1 _lower;
       T2 _upper;

       @property enum bool empty = false;

       this(size_t n, T1 a, T2 b)
       {
             _lower = a;
             _upper = b;
       }

       @property auto ref front()
       {
             assert(!empty);
             return uniform(_lower, _upper);
       }

       void popFront()
       {
       }
}

auto uniformRange(T1, T2)(T1 a, T2 b)
{
       return UniformRange!(T1, T2)(a, b);
}

auto uniformRange(T1, T2)(size_t n, T1 a, T2 b)
{
       return take(UniformRange!(T1, T2)(n, a, b), n);
}


More information about the Digitalmars-d-learn mailing list