D Paste by naryl
Description: Random
Hide line numbers

Create new paste
Post a reply
View replies

Paste:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
import std.math;
import std.algorithm;
import std.c.time;

alias double delegate() Rand;

Rand constant(double value) {
    return { return value; };
}

Rand linear(double mean = 0.5, double delta = 0.5) {

    double x = time(null);
    double M = 2147483647;

    return {
        x = (3123691 * x + 1432512) % M;
        return (1 - 2 * (x / M)) * delta + mean;
    };
}

Rand exponential(double mean) {
    auto next = linear(0.5, 0.5);
    return {
        return -mean * cast(double)log(next());
2    };
}

Rand weighted(double[] weights) {
    auto sum = reduce!("a + b")(0.0, weights);
    foreach (ref weight; weights) {
        weight /= sum;
    }

    sum = 0;
    foreach (ref weight; weights) {
        sum += weight;
        weight = sum;
    }

    auto rand = linear;

    return delegate double() {
        auto val = rand();
        foreach (i, weight; weights) {
            if (val < weight) {
                return cast(double)i;
            }
        }
    };
}

Replies:
No replies posted yet