-
Notifications
You must be signed in to change notification settings - Fork 0
/
distribution.d
1821 lines (1616 loc) · 48.9 KB
/
distribution.d
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Written in the D programming language.
/**
* Implements algorithms for generating random numbers drawn from
* different statistical distributions. Where possible, each random
* _distribution is provided in two different forms:
*
* $(UL
* $(LI as a function, which takes as input the _distribution
* parameters and a uniform RNG, and returns a single value
* drawn from the distribution, and)
* $(LI as a range object, which wraps a uniform RNG instance and
* transforms its output into numbers drawn from the specified
* _distribution.)
* )
*
* Typical reasons for rejecting a function implementation include
* the function needing to hold state between calls to achieve
* adequate performance, or the function needing to allocate memory
* with each call.
*
* As with random number generators, the random _distribution range
* objects implemented here are final classes in order to ensure
* reference semantics. They also assume reference type semantics on
* the part of the RNGs that they wrap: user-supplied value-type RNGs
* may produce unexpected and incorrect behaviour when combined with
* these objects.
*
* Note: $(D hap._random._distribution.dice) uses a different algorithm
* to its $(D std.random) counterpart and so will produce different
* results.
*
* Copyright: © 2008-2011 Andrei Alexandrescu,
* 2013 Chris Cain,
* 2013 Andrej Mitrović,
* 2013-2014 Joseph Rushton Wakeling
*
* License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
*
* Authors: $(WEB erdani.org, Andrei Alexandrescu),
* Chris Cain (discrete _distribution and integral-based uniform),
* Andrej Mitrović (enum-based uniform),
* $(WEB braingam.es, Joseph Rushton Wakeling)
*
* Source: $(HAPSRC hap/random/_distribution.d)
*/
module hap.random.distribution;
import hap.random.generator, hap.random.traits;
import std.range, std.traits;
// dice
/**
* Rolls a random die with relative probabilities stored in $(D proportions).
* Returns the index in $(D proportions) that was chosen.
*
* Example:
* ----
* auto x = dice(0.5, 0.5); // x is 0 or 1 in equal proportions
* auto y = dice(50, 50); // y is 0 or 1 in equal proportions
* auto z = dice(70, 20, 10); // z is 0 70% of the time, 1 20% of the time,
* // and 2 10% of the time
* ----
*
* The range counterpart of $(D dice) is the $(D DiscreteDistribution) class.
*
* Note: given an identically-seeded RNG as input, $(D hap.random.distribution._dice)
* will produce different values to $(D std.random._dice).
*/
size_t dice(UniformRNG, Num)(UniformRNG rng, Num[] proportions...)
if (isNumeric!Num && isForwardRange!UniformRNG)
{
return diceImpl(rng, proportions);
}
/// ditto
size_t dice(UniformRNG, Range)(UniformRNG rng, Range proportions)
if (isUniformRNG!UniformRNG && isForwardRange!Range &&
isNumeric!(ElementType!Range) && !isArray!Range)
{
return diceImpl(rng, proportions);
}
/// ditto
size_t dice(Range)(Range proportions)
if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range)
{
return diceImpl(rndGen, proportions);
}
/// ditto
size_t dice(Num)(Num[] proportions...)
if (isNumeric!Num)
{
return diceImpl(rndGen, proportions);
}
private size_t diceImpl(UniformRNG, Range)(UniformRNG rng, Range proportions)
if (isUniformRNG!UniformRNG && isForwardRange!Range && isNumeric!(ElementType!Range))
{
import std.algorithm, std.exception, hap.random.distribution;
alias T = DiceType!Range;
T sum = reduce!((a, b) { assert(b >= 0); return a + b; })(cast(T) 0, proportions.save);
enforce(sum > 0, "Proportions in a dice cannot sum to zero");
immutable point = uniform!("[)", T, T)(0, sum, rng);
assert(point < sum);
T mass = 0;
size_t i = 0;
foreach (e; proportions)
{
mass += e;
if (point < mass)
{
return i;
}
i++;
}
// this point should not be reached
assert(false);
}
unittest
{
foreach (UniformRNG; UniformRNGTypes)
{
auto rng = new UniformRNG(unpredictableSeed);
foreach (immutable _; 0 .. 100)
{
auto i = dice(rng, 0.0, 100.0);
assert(i == 1);
i = dice(rng, 100.0, 0.0);
assert(i == 0);
i = dice(100U, 0U);
assert(i == 0);
}
import std.typetuple;
foreach(T; TypeTuple!(byte, ubyte, short, ushort, int, uint,
long, ulong, float, double, real))
{
foreach (immutable l; 2 .. 100)
{
auto prop = new T[l];
prop[] = 0;
prop[0] = 10;
prop[$-1] = 10;
foreach (immutable _; 0 .. 100)
{
auto i = dice(rng, prop);
assert(i == 0 || i == l - 1);
}
}
}
}
}
package template DiceType(Range)
if (isInputRange!Range && isNumeric!(ElementType!Range))
{
alias DiceType = DiceType!(ElementType!Range);
}
package template DiceType(T)
if (isNumeric!T)
{
static if (isIntegral!T)
{
static if (is(Largest!(ushort, Unsigned!T) == ushort))
{
alias DiceType = uint;
}
else static if (is(Largest!(ulong, Unsigned!T) == ulong))
{
alias DiceType = ulong;
}
else
{
static assert(false);
}
}
else static if (isFloatingPoint!T)
{
alias DiceType = Largest!(double, T);
}
}
unittest
{
static assert(is(DiceType!byte == uint));
static assert(is(DiceType!ubyte == uint));
static assert(is(DiceType!short == uint));
static assert(is(DiceType!ushort == uint));
static assert(is(DiceType!int == ulong));
static assert(is(DiceType!uint == ulong));
static assert(is(DiceType!float == double));
static assert(is(DiceType!double == double));
static assert(is(DiceType!real == real));
static assert(is(DiceType!(byte[]) == uint));
static assert(is(DiceType!(ubyte[]) == uint));
static assert(is(DiceType!(short[]) == uint));
static assert(is(DiceType!(ushort[]) == uint));
static assert(is(DiceType!(int[]) == ulong));
static assert(is(DiceType!(uint[]) == ulong));
static assert(is(DiceType!(float[]) == double));
static assert(is(DiceType!(double[]) == double));
static assert(is(DiceType!(real[]) == real));
}
/**
* The range equivalent of $(D dice), each element of which is the
* result of the roll of a random die with relative probabilities
* stored in the range $(D proportions). Each successive value of
* $(D front) reflects the index in $(D proportions) that was chosen.
* If no random number generator is specified, the default $(D rndGen)
* will be used as the source of randomness.
*
* This offers a superior option in the event of making many rolls
* of the same die, as the sum and CDF of $(D proportions) only needs
* to be calculated upon construction and not with each call.
*/
final class DiscreteDistribution(SearchPolicy search, T, UniformRNG)
{
private:
SortedRange!(immutable(T)[]) _cumulativeProportions;
UniformRNG _rng;
size_t _value;
public:
enum bool isRandomDistribution = true;
this(Range)(UniformRNG rng, Range proportions)
if (isInputRange!Range && isNumeric!(ElementType!Range))
in
{
assert(!proportions.empty, "Proportions of discrete distribution cannot be empty.");
}
body
{
import std.exception;
_rng = rng;
static if (isImplicitlyConvertible!(typeof(proportions.array), T[]))
{
T[] prop = proportions.array;
}
else
{
import std.algorithm, std.conv;
T[] prop = proportions.map!(to!T).array;
}
alias A = Select!(isFloatingPoint!T, real, T);
A accumulator = 0;
foreach(ref e; prop)
{
assert(e >= 0, "Proportions of discrete distribution cannot be negative.");
debug
{
A preAccumulation = accumulator;
}
accumulator += e;
debug
{
static if (isIntegral!T)
{
enforce(preAccumulation <= accumulator, "Integer overflow detected!");
}
else static if (isFloatingPoint!T)
{
if (e > 0)
{
enforce(accumulator > preAccumulation, "Floating point rounding error detected!");
}
}
else
{
static assert(0);
}
}
e = accumulator;
}
_cumulativeProportions = assumeSorted(assumeUnique(prop)[]);
popFront();
}
this(typeof(this) that)
{
this._cumulativeProportions = that._cumulativeProportions.save;
this._rng = that._rng;
this._value = that._value;
}
/// Range primitives
enum bool empty = false;
/// ditto
size_t front() @property @safe const nothrow pure
{
return _value;
}
/// ditto
void popFront()
{
immutable sum = _cumulativeProportions.back;
immutable point = uniform!"[)"(0, sum, _rng);
assert(point < sum);
_value = _cumulativeProportions.length - _cumulativeProportions.upperBound!search(point).length;
}
/// ditto
static if (isForwardRange!UniformRNG)
{
typeof(this) save() @property
{
auto ret = new typeof(this)(this);
ret._rng = this._rng.save;
return ret;
}
}
}
/// ditto
auto discreteDistribution(SearchPolicy search = SearchPolicy.binarySearch, UniformRNG, Range)
(UniformRNG rng, Range proportions)
if (isInputRange!Range && isNumeric!(ElementType!Range) && isUniformRNG!UniformRNG)
{
return new DiscreteDistribution!(search, DiceType!Range, UniformRNG)(rng, proportions);
}
/// ditto
auto discreteDistribution(SearchPolicy search = SearchPolicy.binarySearch, Range)
(Range proportions)
if (isInputRange!Range && isNumeric!(ElementType!Range))
{
return discreteDistribution(rndGen, proportions);
}
/// ditto
auto discreteDistribution(SearchPolicy search = SearchPolicy.binarySearch, UniformRNG, Num)
(UniformRNG rng, Num[] proportions...)
if (isUniformRNG!UniformRNG && isNumeric!Num)
{
return discreteDistribution(rng, proportions);
}
/// ditto
auto discreteDistribution(SearchPolicy search = SearchPolicy.binarySearch, Num)
(Num[] proportions...)
if (isNumeric!Num)
{
return discreteDistribution(rndGen, proportions);
}
unittest
{
foreach (UniformRNG; UniformRNGTypes)
{
auto rng = new UniformRNG(unpredictableSeed);
foreach (immutable d; discreteDistribution(rng, 100.0, 0.0).take(100))
{
assert(d == 0);
}
foreach (immutable d; discreteDistribution(rng, 0.0, 100.0).take(100))
{
assert(d == 1);
}
foreach (immutable d; discreteDistribution(100, 0).take(100))
{
assert(d == 0);
}
foreach (immutable l; 2 .. 100)
{
auto prop = new uint[l];
prop[] = 0;
prop[0] = prop[$-1] = 20;
foreach (immutable d; discreteDistribution(rng, prop).take(100))
{
assert(d == 0 || d == l - 1);
}
}
import std.typetuple;
foreach(T; TypeTuple!(byte, ubyte, short, ushort, int, uint,
long, ulong, float, double, real))
{
foreach (immutable l; 2 .. 100)
{
auto prop = uniformDistribution!("[]", T, T)(1, 10, rng).take(10).array;
foreach (immutable d; discreteDistribution(rng.save, prop).take(100))
{
assert(d == dice(rng, prop));
}
}
}
// Check .save works
{
auto ddist1 = discreteDistribution(rng, 10.0, 3.0, 9.0);
auto ddist2 = ddist1.save;
assert(ddist1 !is ddist2);
assert(ddist1._rng !is ddist2._rng);
foreach (d1, d2; lockstep(ddist1.take(100), ddist2.take(100)))
{
assert(d1 == d2);
}
}
}
}
/**
* Returns a floating-point number drawn from a _normal (Gaussian)
* distribution with mean $(D mu) and standard deviation $(D sigma).
* If no random number generator is specified, the default $(D rndGen)
* will be used as the source of randomness.
*
* Note that this function uses two variates from the uniform random
* number generator to generate a single normally-distributed variate.
* It is therefore an inefficient means of generating a large number of
* normally-distributed variates. If you wish to draw many variates
* from the _normal distribution, it is better to use the range-based
* $(D normalDistribution) instead.
*/
auto normal(T1, T2)(T1 mu, T2 sigma)
if (isNumeric!T1 && isNumeric!T2)
{
return normal!(T1, T2, Random)(mu, sigma, rndGen);
}
/// ditto
auto normal(T1, T2, UniformRNG)(T1 mu, T2 sigma, UniformRNG rng)
if (isNumeric!T1 && isNumeric!T2 && isUniformRNG!UniformRNG)
{
import std.math;
static if (isFloatingPoint!(CommonType!(T1, T2)))
{
alias T = CommonType!(T1, T2);
}
else
{
alias T = double;
}
immutable T _r1 = uniform01!T(rng);
immutable T _r2 = uniform01!T(rng);
return sqrt(-2 * log(1 - _r2)) * cos(2 * PI * _r1) * sigma + mu;
}
unittest
{
// Compare to behaviour of NormalDistribution
foreach (UniformRNG; UniformRNGTypes)
{
auto rng = new UniformRNG(unpredictableSeed);
auto ndist = normalDistribution(3.29, 7.64, rng.save);
static assert(is(CommonType!(double, double) == double));
foreach (immutable _; 0 .. 100)
{
import std.math;
auto val = normal(3.29, 7.64, rng);
assert(approxEqual(val, ndist.front));
ndist.popFront();
ndist.popFront();
}
}
}
/**
* Provides an infinite range of random numbers distributed according to the
* normal (Gaussian) distribution with mean $(D mu) and standard deviation
* $(D sigma). If no random number generator is specified, the default
* $(D rndGen) will be used as the source of randomness.
*/
final class NormalDistribution(T, UniformRNG)
if (isFloatingPoint!T && isUniformRNG!UniformRNG)
{
private:
alias NormalEngine = NormalEngineBoxMuller;
NormalEngine!T _engine;
UniformRNG _rng;
T _value;
public:
enum bool isRandomDistribution = true;
immutable T mean;
immutable T stdev;
this(T mu, T sigma, UniformRNG rng)
{
import std.exception;
enforce(sigma > 0);
mean = mu;
stdev = sigma;
_rng = rng;
popFront();
}
this(typeof(this) that)
{
this.mean = that.mean;
this.stdev = that.stdev;
this._engine = that._engine;
this._rng = that._rng;
this._value = that._value;
}
/// Range primitives.
enum bool empty = false;
/// ditto
T front() @property @safe const nothrow pure
{
return _value;
}
/// ditto
void popFront()
{
_value = _engine(this.mean, this.stdev, _rng);
}
/// ditto
static if (isForwardRange!UniformRNG)
{
typeof(this) save() @property
{
auto ret = new typeof(this)(this);
ret._rng = this._rng.save;
return ret;
}
}
}
/// ditto
auto normalDistribution(T1, T2, UniformRNG)
(T1 mu, T2 sigma, UniformRNG rng)
if (isNumeric!T1 && isNumeric!T2 && isUniformRNG!UniformRNG)
{
static if (isFloatingPoint!(CommonType!(T1, T2)))
{
alias T = CommonType!(T1, T2);
}
else
{
alias T = double;
}
return new NormalDistribution!(T, UniformRNG)(mu, sigma, rng);
}
/// ditto
auto normalDistribution(T1, T2)
(T1 mu, T2 sigma)
if (isNumeric!T1 && isNumeric!T2)
{
return normalDistribution!(T1, T2, Random)(mu, sigma, rndGen);
}
unittest
{
// check type rules for NormalDistribution
{
auto ndist = normalDistribution(0, 1);
static assert(is(typeof(ndist.front) == double));
}
{
auto ndist = normalDistribution(0.0f, 1);
static assert(is(typeof(ndist.front) == float));
}
{
auto ndist = normalDistribution(0.0, 1);
static assert(is(typeof(ndist.front) == double));
}
{
auto ndist = normalDistribution(0.0L, 1);
static assert(is(typeof(ndist.front) == real));
}
// check save works effectively
foreach (UniformRNG; UniformRNGTypes)
{
auto rng = new UniformRNG(unpredictableSeed);
auto ndist = normalDistribution(3.29, 7.64, rng);
/* Box-Muller generates normal variates a pair at a time.
* advancing to the second of these helps verify that the
* .save method is truly copying the source distribution.
*/
ndist.popFront();
auto ndist2 = ndist.save;
assert(ndist2 !is ndist);
ndist.popFrontN(10);
assert(ndist2.front != ndist.front);
ndist2.popFrontN(10);
assert(ndist2.front == ndist.front);
}
}
/**
* Generates random numbers drawn from a normal (Gaussian) distribution, using
* the Box-Muller Transform method.
*
* This implementation of Box-Muller closely follows that of its counterpart
* in the Boost.Random C++ library and should produce matching results aside
* from discrepancies that arise out of differences in floating-point precision.
*/
private struct NormalEngineBoxMuller(T)
if (isFloatingPoint!T)
{
private:
bool _valid = false;
T _rho, _r1, _r2;
public:
/**
* Generates a single random number drawn from a normal distribution with
* mean $(D mu) and standard deviation $(D sigma), using $(D rng) as the
* source of randomness.
*/
T opCall(UniformRNG)(in T mu, in T sigma, UniformRNG rng)
if (isUniformRNG!UniformRNG)
{
import std.math;
_valid = !_valid;
if (_valid)
{
/* N.B. Traditional Box-Muller asks for random numbers
* in (0, 1], which uniform() can readily supply. We
* instead generate numbers in [0, 1) and use 1 - num
* to match the output of Boost.Random.
*/
_r1 = uniform01!T(rng);
_r2 = uniform01!T(rng);
_rho = sqrt(-2 * log(1 - _r2));
return _rho * cos(2 * PI * _r1) * sigma + mu;
}
else
{
return _rho * sin(2 * PI * _r1) * sigma + mu;
}
}
}
unittest
{
NormalEngineBoxMuller!double engine;
foreach (UniformRNG; UniformRNGTypes)
{
auto rng1 = new UniformRNG(unpredictableSeed);
auto rng2 = rng1.save;
auto rng3 = rng1.save;
double mu = 6.5, sigma = 3.2;
/* The Box-Muller engine produces variates a pair at
* a time. We verify this is true by using a pair of
* pseudo-random number generators sharing the same
* initial state.
*/
auto a1 = engine(mu, sigma, rng1);
auto b2 = engine(mu, sigma, rng2);
// verify that 1st RNG has been called but 2nd has not
assert(rng3.front != rng1.front);
assert(rng3.front == rng2.front);
/* Now, calling with the RNG order reversed should
* produce the same results: only rng2 will get called
* this time.
*/
auto a2 = engine(mu, sigma, rng2);
auto b1 = engine(mu, sigma, rng1);
assert(a1 == a2);
assert(b1 == b2);
assert(rng2.front == rng1.front);
assert(rng3.front != rng2.front);
// verify that the RNGs have each been called twice
rng3.popFrontN(2);
assert(rng3.front == rng2.front);
}
}
/**
* Generates a number between $(D a) and $(D b). The $(D boundaries)
* parameter controls the shape of the interval (open vs. closed on
* either side). Valid values for $(D boundaries) are $(D "[]"), $(D
* "$(LPAREN)]"), $(D "[$(RPAREN)"), and $(D "()"). The default interval
* is closed to the left and open to the right. If no random number
* generator is specified, the default $(D rndGen) will be used as the
* source of randomness.
*
* Example:
*
* ----
* auto gen = Random(unpredictableSeed);
* // Generate an integer in [0, 1023]
* auto a = uniform(0, 1024, gen);
* // Generate a float in [0, 1$(RPAREN)
* auto a = uniform(0.0f, 1.0f, gen);
* ----
*/
auto uniform(string boundaries = "[)", T1, T2)
(T1 a, T2 b)
if (!is(CommonType!(T1, T2) == void))
{
return uniform!(boundaries, T1, T2, Random)(a, b, rndGen);
}
unittest
{
foreach (UniformRNG; UniformRNGTypes)
{
auto rng = new UniformRNG(unpredictableSeed);
foreach (i; 0 .. 20)
{
auto x = uniform(0.0, 15.0, rng);
assert(0 <= x && x < 15);
}
foreach (i; 0 .. 20)
{
auto x = uniform!"[]"('a', 'z', rng);
assert('a' <= x && x <= 'z');
}
foreach (i; 0 .. 20)
{
auto x = uniform('a', 'z', rng);
assert('a' <= x && x < 'z');
}
foreach(i; 0 .. 20)
{
immutable ubyte a = 0;
immutable ubyte b = 15;
auto x = uniform(a, b, rng);
assert(a <= x && x < b);
}
}
}
// Implementation of uniform for floating-point types
/// ditto
auto uniform(string boundaries = "[)", T1, T2, UniformRNG)
(T1 a, T2 b, UniformRNG rng)
if (isFloatingPoint!(CommonType!(T1, T2)) && isUniformRNG!UniformRNG)
out (result)
{
// We assume "[)" as the common case
static if (boundaries[0] == '(')
{
assert(a < result);
}
else
{
assert(a <= result);
}
static if (boundaries[1] == ']')
{
assert(result <= b);
}
else
{
assert(result < b);
}
}
body
{
import std.exception, std.math, std.string : format;
alias NumberType = Unqual!(CommonType!(T1, T2));
static if (boundaries[0] == '(')
{
NumberType _a = nextafter(cast(NumberType) a, NumberType.infinity);
}
else
{
NumberType _a = a;
}
static if (boundaries[1] == ')')
{
NumberType _b = nextafter(cast(NumberType) b, -NumberType.infinity);
}
else
{
NumberType _b = b;
}
enforce(_a <= _b,
format("hap.random.distribution.uniform(): invalid bounding interval %s%s, %s%s",
boundaries[0], a, b, boundaries[1]));
NumberType result =
_a + (_b - _a) * cast(NumberType) (rng.front - rng.min)
/ (rng.max - rng.min);
rng.popFront();
return result;
}
/* Implementation of uniform for integral types.
*
* Description of algorithm and suggestion of correctness:
*
* The modulus operator maps an integer to a small, finite space. For instance, `x
* % 3` will map whatever x is into the range [0 .. 3). 0 maps to 0, 1 maps to 1, 2
* maps to 2, 3 maps to 0, and so on infinitely. As long as the integer is
* uniformly chosen from the infinite space of all non-negative integers then `x %
* 3` will uniformly fall into that range.
*
* (Non-negative is important in this case because some definitions of modulus,
* namely the one used in computers generally, map negative numbers differently to
* (-3 .. 0]. `uniform` does not use negative number modulus, thus we can safely
* ignore that fact.)
*
* The issue with computers is that integers have a finite space they must fit in,
* and our uniformly chosen random number is picked in that finite space. So, that
* method is not sufficient. You can look at it as the integer space being divided
* into "buckets" and every bucket after the first bucket maps directly into that
* first bucket. `[0, 1, 2]`, `[3, 4, 5]`, ... When integers are finite, then the
* last bucket has the chance to be "incomplete": `[uint.max - 3, uint.max - 2,
* uint.max - 1]`, `[uint.max]` ... (the last bucket only has 1!). The issue here
* is that _every_ bucket maps _completely_ to the first bucket except for that
* last one. The last one doesn't have corresponding mappings to 1 or 2, in this
* case, which makes it unfair.
*
* So, the answer is to simply "reroll" if you're in that last bucket, since it's
* the only unfair one. Eventually you'll roll into a fair bucket. Simply, instead
* of the meaning of the last bucket being "maps to `[0]`", it changes to "maps to
* `[0, 1, 2]`", which is precisely what we want.
*
* To generalize, `upperDist` represents the size of our buckets (and, thus, the
* exclusive upper bound for our desired uniform number). `rnum` is a uniformly
* random number picked from the space of integers that a computer can hold (we'll
* say `UpperType` represents that type).
*
* We'll first try to do the mapping into the first bucket by doing `offset = rnum
* % upperDist`. We can figure out the position of the front of the bucket we're in
* by `bucketFront = rnum - offset`.
*
* If we start at `UpperType.max` and walk backwards `upperDist - 1` spaces, then
* the space we land on is the last acceptable position where a full bucket can
* fit:
*
* ```
* bucketFront UpperType.max
* v v
* [..., 0, 1, 2, ..., upperDist - 1]
* ^~~ upperDist - 1 ~~^
* ```
*
* If the bucket starts any later, then it must have lost at least one number and
* at least that number won't be represented fairly.
*
* ```
* bucketFront UpperType.max
* v v
* [..., upperDist - 1, 0, 1, 2, ..., upperDist - 2]
* ^~~~~~~~ upperDist - 1 ~~~~~~~^
* ```
*
* Hence, our condition to reroll is
* `bucketFront > (UpperType.max - (upperDist - 1))`
*/
/// ditto
auto uniform(string boundaries = "[)", T1, T2, UniformRNG)
(T1 a, T2 b, UniformRNG rng)
if ((isIntegral!(CommonType!(T1, T2)) || isSomeChar!(CommonType!(T1, T2)))
&& isUniformRNG!UniformRNG)
out (result)
{
// We assume "[)" as the common case
static if (boundaries[0] == '(')
{
assert(a < result);
}
else
{
assert(a <= result);
}
static if (boundaries[1] == ']')
{
assert(result <= b);
}
else
{
assert(result < b);
}
}
body
{
import std.conv, std.exception;
alias ResultType = Unqual!(CommonType!(T1, T2));
// We handle the case "[)' as the common case, and we adjust all
// other cases to fit it.
static if (boundaries[0] == '(')
{
enforce(a < ResultType.max,
text("hap.random.distribution.uniform(): invalid left bound ", a));
ResultType lower = cast(ResultType) (a + 1);
}
else
{
ResultType lower = a;
}
static if (boundaries[1] == ']')
{
enforce(lower <= b,
text("hap.random.distribution.uniform(): invalid bounding interval ",
boundaries[0], a, ", ", b, boundaries[1]));
/* Cannot use this next optimization with dchar, as dchar
* only partially uses its full bit range
*/
static if (!is(ResultType == dchar))
{
if (b == ResultType.max && lower == ResultType.min)
{
// Special case - all bits are occupied
return uniform!ResultType(rng);
}
}
auto upperDist = unsigned(b - lower) + 1u;
}
else
{
enforce(lower < b,
text("hap.random.distribution.uniform(): invalid bounding interval ",
boundaries[0], a, ", ", b, boundaries[1]));
auto upperDist = unsigned(b - lower);
}
assert(upperDist != 0);
alias UpperType = typeof(upperDist);
static assert(UpperType.min == 0);
UpperType offset, rnum, bucketFront;
do
{
rnum = uniform!UpperType(rng);
offset = rnum % upperDist;
bucketFront = rnum - offset;
} // while we're in an unfair bucket...
while (bucketFront > (UpperType.max - (upperDist - 1)));
return cast(ResultType)(lower + offset);
}
unittest
{
import std.conv, std.typetuple;
foreach (UniformRNG; UniformRNGTypes)
{
auto rng = new UniformRNG(unpredictableSeed);
auto a = uniform(0, 1024, rng);
assert(0 <= a && a <= 1024);
auto b = uniform(0.0f, 1.0f, rng);
assert(0 <= b && b < 1, to!string(b));
auto c = uniform(0.0, 1.0);
assert(0 <= c && c < 1);