Skip to content

Commit 8ed467d

Browse files
committed
PcgRandom: Fix/improve documentation
1 parent dfbdb5b commit 8ed467d

File tree

2 files changed

+23
-12
lines changed

2 files changed

+23
-12
lines changed

doc/lua_api.txt

+3-1
Original file line numberDiff line numberDiff line change
@@ -2865,7 +2865,9 @@ It can be created via `PcgRandom(seed)` or `PcgRandom(seed, sequence)`.
28652865
* `next()`: return next integer random number [`-2147483648`...`2147483647`]
28662866
* `next(min, max)`: return next integer random number [`min`...`max`]
28672867
* `rand_normal_dist(min, max, num_trials=6)`: return normally distributed random number [`min`...`max`]
2868-
* This is only a rough approximation of a normal distribution with mean=(max-min)/2 and variance=1
2868+
* This is only a rough approximation of a normal distribution with:
2869+
* mean = (max - min) / 2, and
2870+
* variance = (((max - min + 1) ^ 2) - 1) / (12 * num_trials)
28692871
* Increasing num_trials improves accuracy of the approximation
28702872

28712873
### `SecureRandom`

src/noise.cpp

+20-11
Original file line numberDiff line numberDiff line change
@@ -93,22 +93,31 @@ u32 PcgRandom::range(u32 bound)
9393
// If the bound is 0, we cover the whole RNG's range
9494
if (bound == 0)
9595
return next();
96+
9697
/*
97-
If the bound is not a multiple of the RNG's range, it may cause bias,
98-
e.g. a RNG has a range from 0 to 3 and we take want a number 0 to 2.
99-
Using rand() % 3, the number 0 would be twice as likely to appear.
100-
With a very large RNG range, the effect becomes less prevalent but
101-
still present. This can be solved by modifying the range of the RNG
102-
to become a multiple of bound by dropping values above the a threshold.
103-
In our example, threshold == 4 - 3 = 1 % 3 == 1, so reject 0, thus
104-
making the range 3 with no bias.
105-
106-
This loop looks dangerous, but will always terminate due to the
107-
RNG's property of uniformity.
98+
This is an optimization of the expression:
99+
0x100000000ull % bound
100+
since 64-bit modulo operations typically much slower than 32.
108101
*/
109102
u32 threshold = -bound % bound;
110103
u32 r;
111104

105+
/*
106+
If the bound is not a multiple of the RNG's range, it may cause bias,
107+
e.g. a RNG has a range from 0 to 3 and we take want a number 0 to 2.
108+
Using rand() % 3, the number 0 would be twice as likely to appear.
109+
With a very large RNG range, the effect becomes less prevalent but
110+
still present.
111+
112+
This can be solved by modifying the range of the RNG to become a
113+
multiple of bound by dropping values above the a threshold.
114+
115+
In our example, threshold == 4 % 3 == 1, so reject values < 1
116+
(that is, 0), thus making the range == 3 with no bias.
117+
118+
This loop may look dangerous, but will always terminate due to the
119+
RNG's property of uniformity.
120+
*/
112121
while ((r = next()) < threshold)
113122
;
114123

0 commit comments

Comments
 (0)