The OpenD Programming Language

piecewiseConstantVar

Piecewise constant variable.

piecewiseConstantVar
(
T
W
)
(,,
bool cumulative = false
)

Examples

import mir.random.engine;
// 50% of the time, generate a random number between 0 and 1
// 50% of the time, generate a random number between 10 and 15
double[] i = [0,  1, 10, 15];
double[] w =   [1,  0,  1];
auto pcv = piecewiseConstantVar(i, w);
static assert(isRandomVariable!(typeof(pcv)));
assert(w == [1, 1, 2]);

int[int] hist;
foreach(_; 0 .. 10000)
    ++hist[cast(int)pcv(rne)];

//import std.stdio;
//import mir.ndslice.topology: repeat;
//foreach(j; 0..cast(int)i[$-1])
//    if(auto count = j in hist)
//        writefln("%2s %s", j, '*'.repeat(*count / 100));

//////// output example /////////
/+
 0 **************************************************
10 *********
11 *********
12 **********
13 *********
14 **********
+/
import mir.random.engine;
Random* gen = threadLocalPtr!Random;
// 50% of the time, generate a random number between 0 and 1
// 50% of the time, generate a random number between 10 and 15
double[] i = [0,  1, 10, 15];
double[] w =   [1,  0,  1];
auto pcv = piecewiseConstantVar(i, w);
assert(w == [1, 1, 2]);

int[int] hist;
foreach(_; 0 .. 10)
    ++hist[cast(int)pcv(gen)];

Meta