The OpenD Programming Language

DiscreteVariable

_Discrete distribution sampler that draws random values from a _discrete distribution given an array of the respective probability density points (weights).

Constructors

this
this(T[] weights, bool cumulative)

DiscreteVariable constructor computes cumulative density points in place without memory allocation.

Members

Functions

max
size_t max()
opCall
size_t opCall(RNG gen)
size_t opCall(RNG* gen)

Samples a value from the discrete distribution using a custom random generator. Complexity: O(log n) where n is the number of weights.

Manifest constants

isRandomVariable
enum isRandomVariable;

Variables

min
enum size_t min;

Examples

import mir.random.engine;
auto gen = Random(unpredictableSeed);
// 10%, 20%, 20%, 40%, 10%
auto weights = [10.0, 20, 20, 40, 10];
auto ds = discreteVar(weights);
static assert(isRandomVariable!(typeof(ds)));

// weight is changed to cumulative sums
assert(weights == [10, 30, 50, 90, 100]);

// sample from the discrete distribution
auto obs = new uint[weights.length];

foreach (i; 0..1000)
    obs[ds(gen)]++;

//import std.stdio;
//writeln(obs);

Cumulative

import mir.random.engine;

auto gen = Random(unpredictableSeed);

auto cumulative = [10.0, 30, 40, 90, 120];
auto ds = discreteVar(cumulative, true);

assert(cumulative == [10.0, 30, 40, 90, 120]);

// sample from the discrete distribution
auto obs = new uint[cumulative.length];
foreach (i; 0..1000)
    obs[ds(gen)]++;
import mir.random.engine;
auto gen = Random(unpredictableSeed);
// 10%, 20%, 20%, 40%, 10%
auto weights = [10.0, 20, 20, 40, 10];
auto ds = discreteVar(weights);

// weight is changed to cumulative sums
assert(weights == [10, 30, 50, 90, 100]);

// sample from the discrete distribution
auto obs = new uint[weights.length];
foreach (i; 0..1000)
    obs[ds(gen)]++;

//import std.stdio;
//writeln(obs);
//[999, 1956, 2063, 3960, 1022]

Meta