57369
|
1 |
/*
|
|
2 |
* Copyright (c) 2013, 2016, 2019, Oracle and/or its affiliates. All rights reserved.
|
|
3 |
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
|
|
4 |
*
|
|
5 |
*
|
|
6 |
*
|
|
7 |
*
|
|
8 |
*
|
|
9 |
*
|
|
10 |
*
|
|
11 |
*
|
|
12 |
*
|
|
13 |
*
|
|
14 |
*
|
|
15 |
*
|
|
16 |
*
|
|
17 |
*
|
|
18 |
*
|
|
19 |
*
|
|
20 |
*
|
|
21 |
*
|
|
22 |
*
|
|
23 |
*
|
|
24 |
*/
|
|
25 |
|
|
26 |
// package java.util;
|
|
27 |
|
|
28 |
import java.util.Spliterator;
|
|
29 |
import java.util.function.Consumer;
|
|
30 |
import java.util.function.IntConsumer;
|
|
31 |
import java.util.function.LongConsumer;
|
|
32 |
import java.util.function.DoubleConsumer;
|
|
33 |
import java.util.stream.StreamSupport;
|
|
34 |
import java.util.stream.IntStream;
|
|
35 |
import java.util.stream.LongStream;
|
|
36 |
import java.util.stream.DoubleStream;
|
|
37 |
// import java.util.DoubleZigguratTables;
|
|
38 |
|
|
39 |
/**
|
|
40 |
* Low-level utility methods helpful for implementing pseudorandom number generators.
|
|
41 |
*
|
|
42 |
* This class is mostly for library writers creating specific implementations of the interface {@link java.util.Rng}.
|
|
43 |
*
|
|
44 |
* @author Guy Steele
|
|
45 |
* @author Doug Lea
|
|
46 |
* @since 1.9
|
|
47 |
*/
|
|
48 |
public class RngSupport {
|
|
49 |
|
|
50 |
/*
|
|
51 |
* Implementation Overview.
|
|
52 |
*
|
|
53 |
* This class provides utility methods and constants frequently
|
|
54 |
* useful in the implentation of pseudorandom number generators
|
|
55 |
* that satisfy the interface {@code java.util.Rng}.
|
|
56 |
*
|
|
57 |
* File organization: First some message strings, then the main
|
|
58 |
* public methods, followed by a non-public base spliterator class.
|
|
59 |
*/
|
|
60 |
|
|
61 |
// IllegalArgumentException messages
|
|
62 |
static final String BadSize = "size must be non-negative";
|
|
63 |
static final String BadDistance = "jump distance must be finite, positive, and an exact integer";
|
|
64 |
static final String BadBound = "bound must be positive";
|
|
65 |
static final String BadFloatingBound = "bound must be finite and positive";
|
|
66 |
static final String BadRange = "bound must be greater than origin";
|
|
67 |
|
|
68 |
/* ---------------- public methods ---------------- */
|
|
69 |
|
|
70 |
/**
|
|
71 |
* Check a {@code long} proposed stream size for validity.
|
|
72 |
*
|
|
73 |
* @param streamSize the proposed stream size
|
|
74 |
* @throws IllegalArgumentException if {@code streamSize} is negative
|
|
75 |
*/
|
|
76 |
public static void checkStreamSize(long streamSize) {
|
|
77 |
if (streamSize < 0L)
|
|
78 |
throw new IllegalArgumentException(BadSize);
|
|
79 |
}
|
|
80 |
|
|
81 |
/**
|
|
82 |
* Check a {@code double} proposed jump distance for validity.
|
|
83 |
*
|
|
84 |
* @param distance the proposed jump distance
|
|
85 |
* @throws IllegalArgumentException if {@code size} not positive,
|
|
86 |
* finite, and an exact integer
|
|
87 |
*/
|
|
88 |
public static void checkJumpDistance(double distance) {
|
|
89 |
if (!(distance > 0.0 && distance < Float.POSITIVE_INFINITY && distance == Math.floor(distance)))
|
|
90 |
throw new IllegalArgumentException(BadDistance);
|
|
91 |
}
|
|
92 |
|
|
93 |
/**
|
|
94 |
* Checks a {@code float} upper bound value for validity.
|
|
95 |
*
|
|
96 |
* @param bound the upper bound (exclusive)
|
|
97 |
* @throws IllegalArgumentException if {@code bound} is not
|
|
98 |
* positive and finite
|
|
99 |
*/
|
|
100 |
public static void checkBound(float bound) {
|
|
101 |
if (!(bound > 0.0 && bound < Float.POSITIVE_INFINITY))
|
|
102 |
throw new IllegalArgumentException(BadFloatingBound);
|
|
103 |
}
|
|
104 |
|
|
105 |
/**
|
|
106 |
* Checks a {@code double} upper bound value for validity.
|
|
107 |
*
|
|
108 |
* @param bound the upper bound (exclusive)
|
|
109 |
* @throws IllegalArgumentException if {@code bound} is not
|
|
110 |
* positive and finite
|
|
111 |
*/
|
|
112 |
public static void checkBound(double bound) {
|
|
113 |
if (!(bound > 0.0 && bound < Double.POSITIVE_INFINITY))
|
|
114 |
throw new IllegalArgumentException(BadFloatingBound);
|
|
115 |
}
|
|
116 |
|
|
117 |
/**
|
|
118 |
* Checks an {@code int} upper bound value for validity.
|
|
119 |
*
|
|
120 |
* @param bound the upper bound (exclusive)
|
|
121 |
* @throws IllegalArgumentException if {@code bound} is not positive
|
|
122 |
*/
|
|
123 |
public static void checkBound(int bound) {
|
|
124 |
if (bound <= 0)
|
|
125 |
throw new IllegalArgumentException(BadBound);
|
|
126 |
}
|
|
127 |
|
|
128 |
/**
|
|
129 |
* Checks a {@code long} upper bound value for validity.
|
|
130 |
*
|
|
131 |
* @param bound the upper bound (exclusive)
|
|
132 |
* @throws IllegalArgumentException if {@code bound} is not positive
|
|
133 |
*/
|
|
134 |
public static void checkBound(long bound) {
|
|
135 |
if (bound <= 0)
|
|
136 |
throw new IllegalArgumentException(BadBound);
|
|
137 |
}
|
|
138 |
|
|
139 |
/**
|
|
140 |
* Checks a {@code float} range for validity.
|
|
141 |
*
|
|
142 |
* @param origin the least value (inclusive) in the range
|
|
143 |
* @param bound the upper bound (exclusive) of the range
|
|
144 |
* @throws IllegalArgumentException unless {@code origin} is finite,
|
|
145 |
* {@code bound} is finite, and {@code bound - origin} is finite
|
|
146 |
*/
|
|
147 |
public static void checkRange(float origin, float bound) {
|
|
148 |
if (!(origin < bound && (bound - origin) < Float.POSITIVE_INFINITY))
|
|
149 |
throw new IllegalArgumentException(BadRange);
|
|
150 |
}
|
|
151 |
|
|
152 |
/**
|
|
153 |
* Checks a {@code double} range for validity.
|
|
154 |
*
|
|
155 |
* @param origin the least value (inclusive) in the range
|
|
156 |
* @param bound the upper bound (exclusive) of the range
|
|
157 |
* @throws IllegalArgumentException unless {@code origin} is finite,
|
|
158 |
* {@code bound} is finite, and {@code bound - origin} is finite
|
|
159 |
*/
|
|
160 |
public static void checkRange(double origin, double bound) {
|
|
161 |
if (!(origin < bound && (bound - origin) < Double.POSITIVE_INFINITY))
|
|
162 |
throw new IllegalArgumentException(BadRange);
|
|
163 |
}
|
|
164 |
|
|
165 |
/**
|
|
166 |
* Checks an {@code int} range for validity.
|
|
167 |
*
|
|
168 |
* @param origin the least value that can be returned
|
|
169 |
* @param bound the upper bound (exclusive) for the returned value
|
|
170 |
* @throws IllegalArgumentException if {@code origin} is greater than
|
|
171 |
* or equal to {@code bound}
|
|
172 |
*/
|
|
173 |
public static void checkRange(int origin, int bound) {
|
|
174 |
if (origin >= bound)
|
|
175 |
throw new IllegalArgumentException(BadRange);
|
|
176 |
}
|
|
177 |
|
|
178 |
/**
|
|
179 |
* Checks a {@code long} range for validity.
|
|
180 |
*
|
|
181 |
* @param origin the least value that can be returned
|
|
182 |
* @param bound the upper bound (exclusive) for the returned value
|
|
183 |
* @throws IllegalArgumentException if {@code origin} is greater than
|
|
184 |
* or equal to {@code bound}
|
|
185 |
*/
|
|
186 |
public static void checkRange(long origin, long bound) {
|
|
187 |
if (origin >= bound)
|
|
188 |
throw new IllegalArgumentException(BadRange);
|
|
189 |
}
|
|
190 |
|
|
191 |
public static long[] convertSeedBytesToLongs(byte[] seed, int n, int z) {
|
|
192 |
final long[] result = new long[n];
|
|
193 |
final int m = Math.min(seed.length, n << 3);
|
|
194 |
// Distribute seed bytes into the words to be formed.
|
|
195 |
for (int j = 0; j < m; j++) {
|
|
196 |
result[j>>3] = (result[j>>3] << 8) | seed[j];
|
|
197 |
}
|
|
198 |
// If there aren't enough seed bytes for all the words we need,
|
|
199 |
// use a SplitMix-style PRNG to fill in the rest.
|
|
200 |
long v = result[0];
|
|
201 |
for (int j = (m + 7) >> 3; j < n; j++) {
|
|
202 |
result[j] = mixMurmur64(v += SILVER_RATIO_64);
|
|
203 |
}
|
|
204 |
// Finally, we need to make sure the last z words are not all zero.
|
|
205 |
search: {
|
|
206 |
for (int j = n - z; j < n; j++) {
|
|
207 |
if (result[j] != 0) break search;
|
|
208 |
}
|
|
209 |
// If they are, fill in using a SplitMix-style PRNG.
|
|
210 |
// Using "& ~1L" in the next line defends against the case z==1
|
|
211 |
// by guaranteeing that the first generated value will be nonzero.
|
|
212 |
long w = result[0] & ~1L;
|
|
213 |
for (int j = n - z; j < n; j++) {
|
|
214 |
result[j] = mixMurmur64(w += SILVER_RATIO_64);
|
|
215 |
}
|
|
216 |
}
|
|
217 |
return result;
|
|
218 |
}
|
|
219 |
|
|
220 |
public static int[] convertSeedBytesToInts(byte[] seed, int n, int z) {
|
|
221 |
final int[] result = new int[n];
|
|
222 |
final int m = Math.min(seed.length, n << 2);
|
|
223 |
// Distribute seed bytes into the words to be formed.
|
|
224 |
for (int j = 0; j < m; j++) {
|
|
225 |
result[j>>2] = (result[j>>2] << 8) | seed[j];
|
|
226 |
}
|
|
227 |
// If there aren't enough seed bytes for all the words we need,
|
|
228 |
// use a SplitMix-style PRNG to fill in the rest.
|
|
229 |
int v = result[0];
|
|
230 |
for (int j = (m + 3) >> 2; j < n; j++) {
|
|
231 |
result[j] = mixMurmur32(v += SILVER_RATIO_32);
|
|
232 |
}
|
|
233 |
// Finally, we need to make sure the last z words are not all zero.
|
|
234 |
search: {
|
|
235 |
for (int j = n - z; j < n; j++) {
|
|
236 |
if (result[j] != 0) break search;
|
|
237 |
}
|
|
238 |
// If they are, fill in using a SplitMix-style PRNG.
|
|
239 |
// Using "& ~1" in the next line defends against the case z==1
|
|
240 |
// by guaranteeing that the first generated value will be nonzero.
|
|
241 |
int w = result[0] & ~1;
|
|
242 |
for (int j = n - z; j < n; j++) {
|
|
243 |
result[j] = mixMurmur32(w += SILVER_RATIO_32);
|
|
244 |
}
|
|
245 |
}
|
|
246 |
return result;
|
|
247 |
}
|
|
248 |
|
|
249 |
/*
|
|
250 |
* Bounded versions of nextX methods used by streams, as well as
|
|
251 |
* the public nextX(origin, bound) methods. These exist mainly to
|
|
252 |
* avoid the need for multiple versions of stream spliterators
|
|
253 |
* across the different exported forms of streams.
|
|
254 |
*/
|
|
255 |
|
|
256 |
/**
|
|
257 |
* This is the form of {@code nextLong} used by a {@code LongStream}
|
|
258 |
* {@code Spliterator} and by the public method
|
|
259 |
* {@code nextLong(origin, bound)}. If {@code origin} is greater
|
|
260 |
* than {@code bound}, then this method simply calls the unbounded
|
|
261 |
* version of {@code nextLong()}, choosing pseudorandomly from
|
|
262 |
* among all 2<sup>64</sup> possible {@code long} values}, and
|
|
263 |
* otherwise uses one or more calls to {@code nextLong()} to
|
|
264 |
* choose a value pseudorandomly from the possible values
|
|
265 |
* between {@code origin} (inclusive) and {@code bound} (exclusive).
|
|
266 |
*
|
|
267 |
* @implNote This method first calls {@code nextLong()} to obtain
|
|
268 |
* a {@code long} value that is assumed to be pseudorandomly
|
|
269 |
* chosen uniformly and independently from the 2<sup>64</sup>
|
|
270 |
* possible {@code long} values (that is, each of the 2<sup>64</sup>
|
|
271 |
* possible long values is equally likely to be chosen).
|
|
272 |
* Under some circumstances (when the specified range is not
|
|
273 |
* a power of 2), {@code nextLong()} may be called additional times
|
|
274 |
* to ensure that that the values in the specified range are
|
|
275 |
* equally likely to be chosen (provided the assumption holds).
|
|
276 |
*
|
|
277 |
* <p> The implementation considers four cases:
|
|
278 |
* <ol>
|
|
279 |
*
|
|
280 |
* <li> If the {@code} bound} is less than or equal to the {@code origin}
|
|
281 |
* (indicated an unbounded form), the 64-bit {@code long} value
|
|
282 |
* obtained from {@code nextLong()} is returned directly.
|
|
283 |
*
|
|
284 |
* <li> Otherwise, if the length <it>n</it> of the specified range is an
|
|
285 |
* exact power of two 2<sup><it>m</it></sup> for some integer
|
|
286 |
* <it>m</it>, then return the sum of {@code origin} and the
|
|
287 |
* <it>m</it> lowest-order bits of the value from {@code nextLong()}.
|
|
288 |
*
|
|
289 |
* <li> Otherwise, if the length <it>n</it> of the specified range
|
|
290 |
* is less than 2<sup>63</sup>, then the basic idea is to use the
|
|
291 |
* remainder modulo <it>n</it> of the value from {@code nextLong()},
|
|
292 |
* but with this approach some values will be over-represented.
|
|
293 |
* Therefore a loop is used to avoid potential bias by rejecting
|
|
294 |
* candidates that are too large. Assuming that the results from
|
|
295 |
* {@code nextLong()} are truly chosen uniformly and independently,
|
|
296 |
* the expected number of iterations will be somewhere between
|
|
297 |
* 1 and 2, depending on the precise value of <it>n</it>.
|
|
298 |
*
|
|
299 |
* <li> Otherwise, the length <it>n</it> of the specified range
|
|
300 |
* cannot be represented as a positive {@code long} value.
|
|
301 |
* A loop repeatedly calls {@code nextlong()} until obtaining
|
|
302 |
* a suitable candidate, Again, the expected number of iterations
|
|
303 |
* is less than 2.
|
|
304 |
*
|
|
305 |
* </ol>
|
|
306 |
*
|
|
307 |
* @param origin the least value that can be produced,
|
|
308 |
* unless greater than or equal to {@code bound}
|
|
309 |
* @param bound the upper bound (exclusive), unless {@code origin}
|
|
310 |
* is greater than or equal to {@code bound}
|
|
311 |
* @return a pseudorandomly chosen {@code long} value,
|
|
312 |
* which will be between {@code origin} (inclusive) and
|
|
313 |
* {@code bound} exclusive unless {@code origin}
|
|
314 |
* is greater than or equal to {@code bound}
|
|
315 |
*/
|
|
316 |
public static long boundedNextLong(Rng rng, long origin, long bound) {
|
|
317 |
long r = rng.nextLong();
|
|
318 |
if (origin < bound) {
|
|
319 |
// It's not case (1).
|
|
320 |
final long n = bound - origin;
|
|
321 |
final long m = n - 1;
|
|
322 |
if ((n & m) == 0L) {
|
|
323 |
// It is case (2): length of range is a power of 2.
|
|
324 |
r = (r & m) + origin;
|
|
325 |
} else if (n > 0L) {
|
|
326 |
// It is case (3): need to reject over-represented candidates.
|
|
327 |
/* This loop takes an unlovable form (but it works):
|
|
328 |
because the first candidate is already available,
|
|
329 |
we need a break-in-the-middle construction,
|
|
330 |
which is concisely but cryptically performed
|
|
331 |
within the while-condition of a body-less for loop. */
|
|
332 |
for (long u = r >>> 1; // ensure nonnegative
|
|
333 |
u + m - (r = u % n) < 0L; // rejection check
|
|
334 |
u = rng.nextLong() >>> 1) // retry
|
|
335 |
;
|
|
336 |
r += origin;
|
|
337 |
}
|
|
338 |
else {
|
|
339 |
// It is case (4): length of range not representable as long.
|
|
340 |
while (r < origin || r >= bound)
|
|
341 |
r = rng.nextLong();
|
|
342 |
}
|
|
343 |
}
|
|
344 |
return r;
|
|
345 |
}
|
|
346 |
|
|
347 |
/**
|
|
348 |
* This is the form of {@code nextLong} used by the public method
|
|
349 |
* {@code nextLong(bound)}. This is essentially a version of
|
|
350 |
* {@code boundedNextLong(origin, bound)} that has been
|
|
351 |
* specialized for the case where the {@code origin} is zero
|
|
352 |
* and the {@code bound} is greater than zero. The value
|
|
353 |
* returned is chosen pseudorandomly from nonnegative integer
|
|
354 |
* values less than {@code bound}.
|
|
355 |
*
|
|
356 |
* @implNote This method first calls {@code nextLong()} to obtain
|
|
357 |
* a {@code long} value that is assumed to be pseudorandomly
|
|
358 |
* chosen uniformly and independently from the 2<sup>64</sup>
|
|
359 |
* possible {@code long} values (that is, each of the 2<sup>64</sup>
|
|
360 |
* possible long values is equally likely to be chosen).
|
|
361 |
* Under some circumstances (when the specified range is not
|
|
362 |
* a power of 2), {@code nextLong()} may be called additional times
|
|
363 |
* to ensure that that the values in the specified range are
|
|
364 |
* equally likely to be chosen (provided the assumption holds).
|
|
365 |
*
|
|
366 |
* <p> The implementation considers two cases:
|
|
367 |
* <ol>
|
|
368 |
*
|
|
369 |
* <li> If {@code bound} is an exact power of two 2<sup><it>m</it></sup>
|
|
370 |
* for some integer <it>m</it>, then return the sum of {@code origin}
|
|
371 |
* and the <it>m</it> lowest-order bits of the value from
|
|
372 |
* {@code nextLong()}.
|
|
373 |
*
|
|
374 |
* <li> Otherwise, the basic idea is to use the remainder modulo
|
|
375 |
* <it>bound</it> of the value from {@code nextLong()},
|
|
376 |
* but with this approach some values will be over-represented.
|
|
377 |
* Therefore a loop is used to avoid potential bias by rejecting
|
|
378 |
* candidates that vare too large. Assuming that the results from
|
|
379 |
* {@code nextLong()} are truly chosen uniformly and independently,
|
|
380 |
* the expected number of iterations will be somewhere between
|
|
381 |
* 1 and 2, depending on the precise value of <it>bound</it>.
|
|
382 |
*
|
|
383 |
* </ol>
|
|
384 |
*
|
|
385 |
* @param bound the upper bound (exclusive); must be greater than zero
|
|
386 |
* @return a pseudorandomly chosen {@code long} value
|
|
387 |
*/
|
|
388 |
public static long boundedNextLong(Rng rng, long bound) {
|
|
389 |
// Specialize boundedNextLong for origin == 0, bound > 0
|
|
390 |
final long m = bound - 1;
|
|
391 |
long r = rng.nextLong();
|
|
392 |
if ((bound & m) == 0L) {
|
|
393 |
// The bound is a power of 2.
|
|
394 |
r &= m;
|
|
395 |
} else {
|
|
396 |
// Must reject over-represented candidates
|
|
397 |
/* This loop takes an unlovable form (but it works):
|
|
398 |
because the first candidate is already available,
|
|
399 |
we need a break-in-the-middle construction,
|
|
400 |
which is concisely but cryptically performed
|
|
401 |
within the while-condition of a body-less for loop. */
|
|
402 |
for (long u = r >>> 1;
|
|
403 |
u + m - (r = u % bound) < 0L;
|
|
404 |
u = rng.nextLong() >>> 1)
|
|
405 |
;
|
|
406 |
}
|
|
407 |
return r;
|
|
408 |
}
|
|
409 |
|
|
410 |
/**
|
|
411 |
* This is the form of {@code nextInt} used by an {@code IntStream}
|
|
412 |
* {@code Spliterator} and by the public method
|
|
413 |
* {@code nextInt(origin, bound)}. If {@code origin} is greater
|
|
414 |
* than {@code bound}, then this method simply calls the unbounded
|
|
415 |
* version of {@code nextInt()}, choosing pseudorandomly from
|
|
416 |
* among all 2<sup>64</sup> possible {@code int} values}, and
|
|
417 |
* otherwise uses one or more calls to {@code nextInt()} to
|
|
418 |
* choose a value pseudorandomly from the possible values
|
|
419 |
* between {@code origin} (inclusive) and {@code bound} (exclusive).
|
|
420 |
*
|
|
421 |
* @implNote The implementation of this method is identical to
|
|
422 |
* the implementation of {@code nextLong(origin, bound)}
|
|
423 |
* except that {@code int} values and the {@code nextInt()}
|
|
424 |
* method are used rather than {@code long} values and the
|
|
425 |
* {@code nextLong()} method.
|
|
426 |
*
|
|
427 |
* @param origin the least value that can be produced,
|
|
428 |
* unless greater than or equal to {@code bound}
|
|
429 |
* @param bound the upper bound (exclusive), unless {@code origin}
|
|
430 |
* is greater than or equal to {@code bound}
|
|
431 |
* @return a pseudorandomly chosen {@code int} value,
|
|
432 |
* which will be between {@code origin} (inclusive) and
|
|
433 |
* {@code bound} exclusive unless {@code origin}
|
|
434 |
* is greater than or equal to {@code bound}
|
|
435 |
*/
|
|
436 |
public static int boundedNextInt(Rng rng, int origin, int bound) {
|
|
437 |
int r = rng.nextInt();
|
|
438 |
if (origin < bound) {
|
|
439 |
// It's not case (1).
|
|
440 |
final int n = bound - origin;
|
|
441 |
final int m = n - 1;
|
|
442 |
if ((n & m) == 0) {
|
|
443 |
// It is case (2): length of range is a power of 2.
|
|
444 |
r = (r & m) + origin;
|
|
445 |
} else if (n > 0) {
|
|
446 |
// It is case (3): need to reject over-represented candidates.
|
|
447 |
for (int u = r >>> 1;
|
|
448 |
u + m - (r = u % n) < 0;
|
|
449 |
u = rng.nextInt() >>> 1)
|
|
450 |
;
|
|
451 |
r += origin;
|
|
452 |
}
|
|
453 |
else {
|
|
454 |
// It is case (4): length of range not representable as long.
|
|
455 |
while (r < origin || r >= bound)
|
|
456 |
|
|
457 |
|
|
458 |
r = rng.nextInt();
|
|
459 |
}
|
|
460 |
}
|
|
461 |
return r;
|
|
462 |
}
|
|
463 |
|
|
464 |
/**
|
|
465 |
* This is the form of {@code nextInt} used by the public method
|
|
466 |
* {@code nextInt(bound)}. This is essentially a version of
|
|
467 |
* {@code boundedNextInt(origin, bound)} that has been
|
|
468 |
* specialized for the case where the {@code origin} is zero
|
|
469 |
* and the {@code bound} is greater than zero. The value
|
|
470 |
* returned is chosen pseudorandomly from nonnegative integer
|
|
471 |
* values less than {@code bound}.
|
|
472 |
*
|
|
473 |
* @implNote The implementation of this method is identical to
|
|
474 |
* the implementation of {@code nextLong(bound)}
|
|
475 |
* except that {@code int} values and the {@code nextInt()}
|
|
476 |
* method are used rather than {@code long} values and the
|
|
477 |
* {@code nextLong()} method.
|
|
478 |
*
|
|
479 |
* @param bound the upper bound (exclusive); must be greater than zero
|
|
480 |
* @return a pseudorandomly chosen {@code long} value
|
|
481 |
*/
|
|
482 |
public static int boundedNextInt(Rng rng, int bound) {
|
|
483 |
// Specialize boundedNextInt for origin == 0, bound > 0
|
|
484 |
final int m = bound - 1;
|
|
485 |
int r = rng.nextInt();
|
|
486 |
if ((bound & m) == 0) {
|
|
487 |
// The bound is a power of 2.
|
|
488 |
r &= m;
|
|
489 |
} else {
|
|
490 |
// Must reject over-represented candidates
|
|
491 |
for (int u = r >>> 1;
|
|
492 |
u + m - (r = u % bound) < 0;
|
|
493 |
u = rng.nextInt() >>> 1)
|
|
494 |
;
|
|
495 |
}
|
|
496 |
return r;
|
|
497 |
}
|
|
498 |
|
|
499 |
/**
|
|
500 |
* This is the form of {@code nextDouble} used by a {@code DoubleStream}
|
|
501 |
* {@code Spliterator} and by the public method
|
|
502 |
* {@code nextDouble(origin, bound)}. If {@code origin} is greater
|
|
503 |
* than {@code bound}, then this method simply calls the unbounded
|
|
504 |
* version of {@code nextDouble()}, and otherwise scales and translates
|
|
505 |
* the result of a call to {@code nextDouble()} so that it lies
|
|
506 |
* between {@code origin} (inclusive) and {@code bound} (exclusive).
|
|
507 |
*
|
|
508 |
* @implNote The implementation considers two cases:
|
|
509 |
* <ol>
|
|
510 |
*
|
|
511 |
* <li> If the {@code bound} is less than or equal to the {@code origin}
|
|
512 |
* (indicated an unbounded form), the 64-bit {@code double} value
|
|
513 |
* obtained from {@code nextDouble()} is returned directly.
|
|
514 |
*
|
|
515 |
* <li> Otherwise, the result of a call to {@code nextDouble} is
|
|
516 |
* multiplied by {@code (bound - origin)}, then {@code origin}
|
|
517 |
* is added, and then if this this result is not less than
|
|
518 |
* {@code bound} (which can sometimes occur because of rounding),
|
|
519 |
* it is replaced with the largest {@code double} value that
|
|
520 |
* is less than {@code bound}.
|
|
521 |
*
|
|
522 |
* </ol>
|
|
523 |
*
|
|
524 |
* @param origin the least value that can be produced,
|
|
525 |
* unless greater than or equal to {@code bound}; must be finite
|
|
526 |
* @param bound the upper bound (exclusive), unless {@code origin}
|
|
527 |
* is greater than or equal to {@code bound}; must be finite
|
|
528 |
* @return a pseudorandomly chosen {@code double} value,
|
|
529 |
* which will be between {@code origin} (inclusive) and
|
|
530 |
* {@code bound} exclusive unless {@code origin}
|
|
531 |
* is greater than or equal to {@code bound},
|
|
532 |
* in which case it will be between 0.0 (inclusive)
|
|
533 |
* and 1.0 (exclusive)
|
|
534 |
*/
|
|
535 |
public static double boundedNextDouble(Rng rng, double origin, double bound) {
|
|
536 |
double r = rng.nextDouble();
|
|
537 |
if (origin < bound) {
|
|
538 |
r = r * (bound - origin) + origin;
|
|
539 |
if (r >= bound) // may need to correct a rounding problem
|
|
540 |
r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
|
|
541 |
}
|
|
542 |
return r;
|
|
543 |
}
|
|
544 |
|
|
545 |
/**
|
|
546 |
* This is the form of {@code nextDouble} used by the public method
|
|
547 |
* {@code nextDouble(bound)}. This is essentially a version of
|
|
548 |
* {@code boundedNextDouble(origin, bound)} that has been
|
|
549 |
* specialized for the case where the {@code origin} is zero
|
|
550 |
* and the {@code bound} is greater than zero.
|
|
551 |
*
|
|
552 |
* @implNote The result of a call to {@code nextDouble} is
|
|
553 |
* multiplied by {@code bound}, and then if this result is
|
|
554 |
* not less than {@code bound} (which can sometimes occur
|
|
555 |
* because of rounding), it is replaced with the largest
|
|
556 |
* {@code double} value that is less than {@code bound}.
|
|
557 |
*
|
|
558 |
* @param bound the upper bound (exclusive); must be finite and
|
|
559 |
* greater than zero
|
|
560 |
* @return a pseudorandomly chosen {@code double} value
|
|
561 |
* between zero (inclusive) and {@code bound} (exclusive)
|
|
562 |
*/
|
|
563 |
public static double boundedNextDouble(Rng rng, double bound) {
|
|
564 |
// Specialize boundedNextDouble for origin == 0, bound > 0
|
|
565 |
double r = rng.nextDouble();
|
|
566 |
r = r * bound;
|
|
567 |
if (r >= bound) // may need to correct a rounding problem
|
|
568 |
r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
|
|
569 |
return r;
|
|
570 |
}
|
|
571 |
|
|
572 |
/**
|
|
573 |
* This is the form of {@code nextFloat} used by a {@code FloatStream}
|
|
574 |
* {@code Spliterator} (if there were any) and by the public method
|
|
575 |
* {@code nextFloat(origin, bound)}. If {@code origin} is greater
|
|
576 |
* than {@code bound}, then this method simply calls the unbounded
|
|
577 |
* version of {@code nextFloat()}, and otherwise scales and translates
|
|
578 |
* the result of a call to {@code nextFloat()} so that it lies
|
|
579 |
* between {@code origin} (inclusive) and {@code bound} (exclusive).
|
|
580 |
*
|
|
581 |
* @implNote The implementation of this method is identical to
|
|
582 |
* the implementation of {@code nextDouble(origin, bound)}
|
|
583 |
* except that {@code float} values and the {@code nextFloat()}
|
|
584 |
* method are used rather than {@code double} values and the
|
|
585 |
* {@code nextDouble()} method.
|
|
586 |
*
|
|
587 |
* @param origin the least value that can be produced,
|
|
588 |
* unless greater than or equal to {@code bound}; must be finite
|
|
589 |
* @param bound the upper bound (exclusive), unless {@code origin}
|
|
590 |
* is greater than or equal to {@code bound}; must be finite
|
|
591 |
* @return a pseudorandomly chosen {@code float} value,
|
|
592 |
* which will be between {@code origin} (inclusive) and
|
|
593 |
* {@code bound} exclusive unless {@code origin}
|
|
594 |
* is greater than or equal to {@code bound},
|
|
595 |
* in which case it will be between 0.0 (inclusive)
|
|
596 |
* and 1.0 (exclusive)
|
|
597 |
*/
|
|
598 |
public static float boundedNextFloat(Rng rng, float origin, float bound) {
|
|
599 |
float r = rng.nextFloat();
|
|
600 |
if (origin < bound) {
|
|
601 |
r = r * (bound - origin) + origin;
|
|
602 |
if (r >= bound) // may need to correct a rounding problem
|
|
603 |
r = Float.intBitsToFloat(Float.floatToIntBits(bound) - 1);
|
|
604 |
}
|
|
605 |
return r;
|
|
606 |
}
|
|
607 |
|
|
608 |
/**
|
|
609 |
* This is the form of {@code nextFloat} used by the public method
|
|
610 |
* {@code nextFloat(bound)}. This is essentially a version of
|
|
611 |
* {@code boundedNextFloat(origin, bound)} that has been
|
|
612 |
* specialized for the case where the {@code origin} is zero
|
|
613 |
* and the {@code bound} is greater than zero.
|
|
614 |
*
|
|
615 |
* @implNote The implementation of this method is identical to
|
|
616 |
* the implementation of {@code nextDouble(bound)}
|
|
617 |
* except that {@code float} values and the {@code nextFloat()}
|
|
618 |
* method are used rather than {@code double} values and the
|
|
619 |
* {@code nextDouble()} method.
|
|
620 |
*
|
|
621 |
* @param bound the upper bound (exclusive); must be finite and
|
|
622 |
* greater than zero
|
|
623 |
* @return a pseudorandomly chosen {@code float} value
|
|
624 |
* between zero (inclusive) and {@code bound} (exclusive)
|
|
625 |
*/
|
|
626 |
public static float boundedNextFloat(Rng rng, float bound) {
|
|
627 |
// Specialize boundedNextFloat for origin == 0, bound > 0
|
|
628 |
float r = rng.nextFloat();
|
|
629 |
r = r * bound;
|
|
630 |
if (r >= bound) // may need to correct a rounding problem
|
|
631 |
r = Float.intBitsToFloat(Float.floatToIntBits(bound) - 1);
|
|
632 |
return r;
|
|
633 |
}
|
|
634 |
|
|
635 |
// The following decides which of two strategies initialSeed() will use.
|
|
636 |
private static boolean secureRandomSeedRequested() {
|
|
637 |
String pp = java.security.AccessController.doPrivileged(
|
|
638 |
new sun.security.action.GetPropertyAction(
|
|
639 |
"java.util.secureRandomSeed"));
|
|
640 |
return (pp != null && pp.equalsIgnoreCase("true"));
|
|
641 |
}
|
|
642 |
|
|
643 |
private static final boolean useSecureRandomSeed = secureRandomSeedRequested();
|
|
644 |
|
|
645 |
/**
|
|
646 |
* Returns a {@code long} value (chosen from some
|
|
647 |
* machine-dependent entropy source) that may be useful for
|
|
648 |
* initializing a source of seed values for instances of {@code Rng}
|
|
649 |
* created by zero-argument constructors. (This method should
|
|
650 |
* <it>not</it> be called repeatedly, once per constructed
|
|
651 |
* object; at most it should be called once per class.)
|
|
652 |
*
|
|
653 |
* @return a {@code long} value, randomly chosen using
|
|
654 |
* appropriate environmental entropy
|
|
655 |
*/
|
|
656 |
public static long initialSeed() {
|
|
657 |
if (useSecureRandomSeed) {
|
|
658 |
byte[] seedBytes = java.security.SecureRandom.getSeed(8);
|
|
659 |
long s = (long)(seedBytes[0]) & 0xffL;
|
|
660 |
for (int i = 1; i < 8; ++i)
|
|
661 |
s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
|
|
662 |
return s;
|
|
663 |
}
|
|
664 |
return (mixStafford13(System.currentTimeMillis()) ^
|
|
665 |
mixStafford13(System.nanoTime()));
|
|
666 |
}
|
|
667 |
|
|
668 |
/**
|
|
669 |
* The fractional part (first 32 or 64 bits, then forced odd) of
|
|
670 |
* the golden ratio (1+sqrt(5))/2 and of the silver ratio 1+sqrt(2).
|
|
671 |
* Useful for producing good Weyl sequences or as arbitrary nonzero values.
|
|
672 |
*/
|
|
673 |
public static final int GOLDEN_RATIO_32 = 0x9e3779b9;
|
|
674 |
public static final long GOLDEN_RATIO_64 = 0x9e3779b97f4a7c15L;
|
|
675 |
public static final int SILVER_RATIO_32 = 0x6A09E667;
|
|
676 |
public static final long SILVER_RATIO_64 = 0x6A09E667F3BCC909L;
|
|
677 |
|
|
678 |
/**
|
|
679 |
* Computes the 64-bit mixing function for MurmurHash3.
|
|
680 |
* This is a 64-bit hashing function with excellent avalanche statistics.
|
|
681 |
* https://github.com/aappleby/smhasher/wiki/MurmurHash3
|
|
682 |
*
|
|
683 |
* Note that if the argument {@code z} is 0, the result is 0.
|
|
684 |
*
|
|
685 |
* @param z any long value
|
|
686 |
*
|
|
687 |
* @return the result of hashing z
|
|
688 |
*/
|
|
689 |
public static long mixMurmur64(long z) {
|
|
690 |
z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
|
|
691 |
z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
|
|
692 |
return z ^ (z >>> 33);
|
|
693 |
}
|
|
694 |
|
|
695 |
/**
|
|
696 |
* Computes Stafford variant 13 of the 64-bit mixing function for MurmurHash3.
|
|
697 |
* This is a 64-bit hashing function with excellent avalanche statistics.
|
|
698 |
* http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
|
|
699 |
*
|
|
700 |
* Note that if the argument {@code z} is 0, the result is 0.
|
|
701 |
*
|
|
702 |
* @param z any long value
|
|
703 |
*
|
|
704 |
* @return the result of hashing z
|
|
705 |
*/
|
|
706 |
public static long mixStafford13(long z) {
|
|
707 |
z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
|
|
708 |
z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
|
|
709 |
return z ^ (z >>> 31);
|
|
710 |
}
|
|
711 |
|
|
712 |
/**
|
|
713 |
* Computes Doug Lea's 64-bit mixing function.
|
|
714 |
* This is a 64-bit hashing function with excellent avalanche statistics.
|
|
715 |
* It has the advantages of using the same multiplicative constant twice
|
|
716 |
* and of using only 32-bit shifts.
|
|
717 |
*
|
|
718 |
* Note that if the argument {@code z} is 0, the result is 0.
|
|
719 |
*
|
|
720 |
* @param z any long value
|
|
721 |
*
|
|
722 |
* @return the result of hashing z
|
|
723 |
*/
|
|
724 |
public static long mixLea64(long z) {
|
|
725 |
z = (z ^ (z >>> 32)) * 0xdaba0b6eb09322e3L;
|
|
726 |
z = (z ^ (z >>> 32)) * 0xdaba0b6eb09322e3L;
|
|
727 |
return z ^ (z >>> 32);
|
|
728 |
}
|
|
729 |
|
|
730 |
/**
|
|
731 |
* Computes the 32-bit mixing function for MurmurHash3.
|
|
732 |
* This is a 32-bit hashing function with excellent avalanche statistics.
|
|
733 |
* https://github.com/aappleby/smhasher/wiki/MurmurHash3
|
|
734 |
*
|
|
735 |
* Note that if the argument {@code z} is 0, the result is 0.
|
|
736 |
*
|
|
737 |
* @param z any long value
|
|
738 |
*
|
|
739 |
* @return the result of hashing z
|
|
740 |
*/
|
|
741 |
public static int mixMurmur32(int z) {
|
|
742 |
z = (z ^ (z >>> 16)) * 0x85ebca6b;
|
|
743 |
z = (z ^ (z >>> 13)) * 0xc2b2ae35;
|
|
744 |
return z ^ (z >>> 16);
|
|
745 |
}
|
|
746 |
|
|
747 |
/**
|
|
748 |
* Computes Doug Lea's 32-bit mixing function.
|
|
749 |
* This is a 32-bit hashing function with excellent avalanche statistics.
|
|
750 |
* It has the advantages of using the same multiplicative constant twice
|
|
751 |
* and of using only 16-bit shifts.
|
|
752 |
*
|
|
753 |
* Note that if the argument {@code z} is 0, the result is 0.
|
|
754 |
*
|
|
755 |
* @param z any long value
|
|
756 |
*
|
|
757 |
* @return the result of hashing z
|
|
758 |
*/
|
|
759 |
public static int mixLea32(int z) {
|
|
760 |
z = (z ^ (z >>> 16)) * 0xd36d884b;
|
|
761 |
z = (z ^ (z >>> 16)) * 0xd36d884b;
|
|
762 |
return z ^ (z >>> 16);
|
|
763 |
}
|
|
764 |
|
|
765 |
// Non-public (package only) support for spliterators needed by AbstractSplittableRng
|
|
766 |
// and AbstractArbitrarilyJumpableRng and AbstractSharedRng
|
|
767 |
|
|
768 |
/**
|
|
769 |
* Base class for making Spliterator classes for streams of randomly chosen values.
|
|
770 |
*/
|
|
771 |
static abstract class RandomSpliterator {
|
|
772 |
long index;
|
|
773 |
final long fence;
|
|
774 |
|
|
775 |
RandomSpliterator(long index, long fence) {
|
|
776 |
this.index = index; this.fence = fence;
|
|
777 |
}
|
|
778 |
|
|
779 |
public long estimateSize() {
|
|
780 |
return fence - index;
|
|
781 |
}
|
|
782 |
|
|
783 |
public int characteristics() {
|
|
784 |
return (Spliterator.SIZED | Spliterator.SUBSIZED |
|
|
785 |
Spliterator.NONNULL | Spliterator.IMMUTABLE);
|
|
786 |
}
|
|
787 |
}
|
|
788 |
|
|
789 |
|
|
790 |
/*
|
|
791 |
* Implementation support for nextExponential() and nextGaussian() methods of Rng.
|
|
792 |
*
|
|
793 |
* Each is implemented using McFarland's fast modified ziggurat algorithm (largely
|
|
794 |
* table-driven, with rare cases handled by computation and rejection sampling).
|
|
795 |
* Walker's alias method for sampling a discrete distribution also plays a role.
|
|
796 |
*
|
|
797 |
* The tables themselves, as well as a number of associated parameters, are defined
|
|
798 |
* in class java.util.DoubleZigguratTables, which is automatically generated by the
|
|
799 |
* program create_ziggurat_tables.c (which takes only a few seconds to run).
|
|
800 |
*
|
|
801 |
* For more information about the algorithms, see these articles:
|
|
802 |
*
|
|
803 |
* Christopher D. McFarland. 2016 (published online 24 Jun 2015). A modified ziggurat
|
|
804 |
* algorithm for generating exponentially and normally distributed pseudorandom numbers.
|
|
805 |
* Journal of Statistical Computation and Simulation 86 (7), pages 1281-1294.
|
|
806 |
* https://www.tandfonline.com/doi/abs/10.1080/00949655.2015.1060234
|
|
807 |
* Also at https://arxiv.org/abs/1403.6870 (26 March 2014).
|
|
808 |
*
|
|
809 |
* Alastair J. Walker. 1977. An efficient method for generating discrete random
|
|
810 |
* variables with general distributions. ACM Trans. Math. Software 3, 3
|
|
811 |
* (September 1977), 253-256. DOI: https://doi.org/10.1145/355744.355749
|
|
812 |
*
|
|
813 |
* Certain details of these algorithms depend critically on the quality of the
|
|
814 |
* low-order bits delivered by NextLong(). These algorithms should not be used
|
|
815 |
* with RNG algorithms (such as a simple Linear Congruential Generator) whose
|
|
816 |
* low-order output bits do not have good statistical quality.
|
|
817 |
*/
|
|
818 |
|
|
819 |
// Implementation support for nextExponential()
|
|
820 |
|
|
821 |
static double computeNextExponential(Rng rng) {
|
|
822 |
long U1 = rng.nextLong();
|
|
823 |
// Experimentation on a variety of machines indicates that it is overall much faster
|
|
824 |
// to do the following & and < operations on longs rather than first cast U1 to int
|
|
825 |
// (but then we need to cast to int before doing the array indexing operation).
|
|
826 |
long i = U1 & DoubleZigguratTables.exponentialLayerMask;
|
|
827 |
if (i < DoubleZigguratTables.exponentialNumberOfLayers) {
|
|
828 |
// This is the fast path (occurring more than 98% of the time). Make an early exit.
|
|
829 |
return DoubleZigguratTables.exponentialX[(int)i] * (U1 >>> 1);
|
|
830 |
}
|
|
831 |
// We didn't use the upper part of U1 after all. We'll be able to use it later.
|
|
832 |
|
|
833 |
for (double extra = 0.0; ; ) {
|
|
834 |
// Use Walker's alias method to sample an (unsigned) integer j from a discrete
|
|
835 |
// probability distribution that includes the tail and all the ziggurat overhangs;
|
|
836 |
// j will be less than DoubleZigguratTables.exponentialNumberOfLayers + 1.
|
|
837 |
long UA = rng.nextLong();
|
|
838 |
int j = (int)UA & DoubleZigguratTables.exponentialAliasMask;
|
|
839 |
if (UA >= DoubleZigguratTables.exponentialAliasThreshold[j]) {
|
|
840 |
j = DoubleZigguratTables.exponentialAliasMap[j] & DoubleZigguratTables.exponentialSignCorrectionMask;
|
|
841 |
}
|
|
842 |
if (j > 0) { // Sample overhang j
|
|
843 |
// For the exponential distribution, every overhang is convex.
|
|
844 |
final double[] X = DoubleZigguratTables.exponentialX;
|
|
845 |
final double[] Y = DoubleZigguratTables.exponentialY;
|
|
846 |
for (;; U1 = (rng.nextLong() >>> 1)) {
|
|
847 |
long U2 = (rng.nextLong() >>> 1);
|
|
848 |
// Compute the actual x-coordinate of the randomly chosen point.
|
|
849 |
double x = (X[j] * 0x1.0p63) + ((X[j-1] - X[j]) * (double)U1);
|
|
850 |
// Does the point lie below the curve?
|
|
851 |
long Udiff = U2 - U1;
|
|
852 |
if (Udiff < 0) {
|
|
853 |
// We picked a point in the upper-right triangle. None of those can be accepted.
|
|
854 |
// So remap the point into the lower-left triangle and try that.
|
|
855 |
// In effect, we swap U1 and U2, and invert the sign of Udiff.
|
|
856 |
Udiff = -Udiff;
|
|
857 |
U2 = U1;
|
|
858 |
U1 -= Udiff;
|
|
859 |
}
|
|
860 |
if (Udiff >= DoubleZigguratTables.exponentialConvexMargin) {
|
|
861 |
return x + extra; // The chosen point is way below the curve; accept it.
|
|
862 |
}
|
|
863 |
// Compute the actual y-coordinate of the randomly chosen point.
|
|
864 |
double y = (Y[j] * 0x1.0p63) + ((Y[j] - Y[j-1]) * (double)U2);
|
|
865 |
// Now see how that y-coordinate compares to the curve
|
|
866 |
if (y <= Math.exp(-x)) {
|
|
867 |
return x + extra; // The chosen point is below the curve; accept it.
|
|
868 |
}
|
|
869 |
// Otherwise, we reject this sample and have to try again.
|
|
870 |
}
|
|
871 |
}
|
|
872 |
// We are now committed to sampling from the tail. We could do a recursive call
|
|
873 |
// and then add X[0] but we save some time and stack space by using an iterative loop.
|
|
874 |
extra += DoubleZigguratTables.exponentialX0;
|
|
875 |
// This is like the first five lines of this method, but if it returns, it first adds "extra".
|
|
876 |
U1 = rng.nextLong();
|
|
877 |
i = U1 & DoubleZigguratTables.exponentialLayerMask;
|
|
878 |
if (i < DoubleZigguratTables.exponentialNumberOfLayers) {
|
|
879 |
return DoubleZigguratTables.exponentialX[(int)i] * (U1 >>> 1) + extra;
|
|
880 |
}
|
|
881 |
}
|
|
882 |
}
|
|
883 |
|
|
884 |
// Implementation support for nextGaussian()
|
|
885 |
|
|
886 |
static double computeNextGaussian(Rng rng) {
|
|
887 |
long U1 = rng.nextLong();
|
|
888 |
// Experimentation on a variety of machines indicates that it is overall much faster
|
|
889 |
// to do the following & and < operations on longs rather than first cast U1 to int
|
|
890 |
// (but then we need to cast to int before doing the array indexing operation).
|
|
891 |
long i = U1 & DoubleZigguratTables.normalLayerMask;
|
|
892 |
|
|
893 |
if (i < DoubleZigguratTables.normalNumberOfLayers) {
|
|
894 |
// This is the fast path (occurring more than 98% of the time). Make an early exit.
|
|
895 |
return DoubleZigguratTables.normalX[(int)i] * U1; // Note that the sign bit of U1 is used here.
|
|
896 |
}
|
|
897 |
// We didn't use the upper part of U1 after all.
|
|
898 |
// Pull U1 apart into a sign bit and a 63-bit value for later use.
|
|
899 |
double signBit = (U1 >= 0) ? 1.0 : -1.0;
|
|
900 |
U1 = (U1 << 1) >>> 1;
|
|
901 |
|
|
902 |
// Use Walker's alias method to sample an (unsigned) integer j from a discrete
|
|
903 |
// probability distribution that includes the tail and all the ziggurat overhangs;
|
|
904 |
// j will be less than DoubleZigguratTables.normalNumberOfLayers + 1.
|
|
905 |
long UA = rng.nextLong();
|
|
906 |
int j = (int)UA & DoubleZigguratTables.normalAliasMask;
|
|
907 |
if (UA >= DoubleZigguratTables.normalAliasThreshold[j]) {
|
|
908 |
j = DoubleZigguratTables.normalAliasMap[j] & DoubleZigguratTables.normalSignCorrectionMask;
|
|
909 |
}
|
|
910 |
|
|
911 |
double x;
|
|
912 |
// Now the goal is to choose the result, which will be multiplied by signBit just before return.
|
|
913 |
|
|
914 |
// There are four kinds of overhangs:
|
|
915 |
//
|
|
916 |
// j == 0 : Sample from tail
|
|
917 |
// 0 < j < normalInflectionIndex : Overhang is convex; can reject upper-right triangle
|
|
918 |
// j == normalInflectionIndex : Overhang includes the inflection point
|
|
919 |
// j > normalInflectionIndex : Overhang is concave; can accept point in lower-left triangle
|
|
920 |
//
|
|
921 |
// Choose one of four loops to compute x, each specialized for a specific kind of overhang.
|
|
922 |
// Conditional statements are arranged such that the more likely outcomes are first.
|
|
923 |
|
|
924 |
// In the three cases other than the tail case:
|
|
925 |
// U1 represents a fraction (scaled by 2**63) of the width of rectangle measured from the left.
|
|
926 |
// U2 represents a fraction (scaled by 2**63) of the height of rectangle measured from the top.
|
|
927 |
// Together they indicate a randomly chosen point within the rectangle.
|
|
928 |
|
|
929 |
final double[] X = DoubleZigguratTables.normalX;
|
|
930 |
final double[] Y = DoubleZigguratTables.normalY;
|
|
931 |
if (j > DoubleZigguratTables.normalInflectionIndex) { // Concave overhang
|
|
932 |
for (;; U1 = (rng.nextLong() >>> 1)) {
|
|
933 |
long U2 = (rng.nextLong() >>> 1);
|
|
934 |
// Compute the actual x-coordinate of the randomly chosen point.
|
|
935 |
x = (X[j] * 0x1.0p63) + ((X[j-1] - X[j]) * (double)U1);
|
|
936 |
// Does the point lie below the curve?
|
|
937 |
long Udiff = U2 - U1;
|
|
938 |
if (Udiff >= 0) {
|
|
939 |
break; // The chosen point is in the lower-left triangle; accept it.
|
|
940 |
}
|
|
941 |
if (Udiff <= -DoubleZigguratTables.normalConcaveMargin) {
|
|
942 |
continue; // The chosen point is way above the curve; reject it.
|
|
943 |
}
|
|
944 |
// Compute the actual y-coordinate of the randomly chosen point.
|
|
945 |
double y = (Y[j] * 0x1.0p63) + ((Y[j] - Y[j-1]) * (double)U2);
|
|
946 |
// Now see how that y-coordinate compares to the curve
|
|
947 |
if (y <= Math.exp(-0.5*x*x)) {
|
|
948 |
break; // The chosen point is below the curve; accept it.
|
|
949 |
}
|
|
950 |
// Otherwise, we reject this sample and have to try again.
|
|
951 |
}
|
|
952 |
} else if (j == 0) { // Tail
|
|
953 |
// Tail-sampling method of Marsaglia and Tsang. See any one of:
|
|
954 |
// Marsaglia and Tsang. 1984. A fast, easily implemented method for sampling from decreasing
|
|
955 |
// or symmetric unimodal density functions. SIAM J. Sci. Stat. Comput. 5, 349-359.
|
|
956 |
// Marsaglia and Tsang. 1998. The Monty Python method for generating random variables.
|
|
957 |
// ACM Trans. Math. Softw. 24, 3 (September 1998), 341-350. See page 342, step (4).
|
|
958 |
// http://doi.org/10.1145/292395.292453
|
|
959 |
// Thomas, Luk, Leong, and Villasenor. 2007. Gaussian random number generators.
|
|
960 |
// ACM Comput. Surv. 39, 4, Article 11 (November 2007). See Algorithm 16.
|
|
961 |
// http://doi.org/10.1145/1287620.1287622
|
|
962 |
// Compute two separate random exponential samples and then compare them in certain way.
|
|
963 |
do {
|
|
964 |
x = (1.0 / DoubleZigguratTables.normalX0) * computeNextExponential(rng);
|
|
965 |
} while (computeNextExponential(rng) < 0.5*x*x);
|
|
966 |
x += DoubleZigguratTables.normalX0;
|
|
967 |
} else if (j < DoubleZigguratTables.normalInflectionIndex) { // Convex overhang
|
|
968 |
for (;; U1 = (rng.nextLong() >>> 1)) {
|
|
969 |
long U2 = (rng.nextLong() >>> 1);
|
|
970 |
// Compute the actual x-coordinate of the randomly chosen point.
|
|
971 |
x = (X[j] * 0x1.0p63) + ((X[j-1] - X[j]) * (double)U1);
|
|
972 |
// Does the point lie below the curve?
|
|
973 |
long Udiff = U2 - U1;
|
|
974 |
if (Udiff < 0) {
|
|
975 |
// We picked a point in the upper-right triangle. None of those can be accepted.
|
|
976 |
// So remap the point into the lower-left triangle and try that.
|
|
977 |
// In effect, we swap U1 and U2, and invert the sign of Udiff.
|
|
978 |
Udiff = -Udiff;
|
|
979 |
U2 = U1;
|
|
980 |
U1 -= Udiff;
|
|
981 |
}
|
|
982 |
if (Udiff >= DoubleZigguratTables.normalConvexMargin) {
|
|
983 |
break; // The chosen point is way below the curve; accept it.
|
|
984 |
}
|
|
985 |
// Compute the actual y-coordinate of the randomly chosen point.
|
|
986 |
double y = (Y[j] * 0x1.0p63) + ((Y[j] - Y[j-1]) * (double)U2);
|
|
987 |
// Now see how that y-coordinate compares to the curve
|
|
988 |
if (y <= Math.exp(-0.5*x*x)) break; // The chosen point is below the curve; accept it.
|
|
989 |
// Otherwise, we reject this sample and have to try again.
|
|
990 |
}
|
|
991 |
} else {
|
|
992 |
// The overhang includes the inflection point, so the curve is both convex and concave
|
|
993 |
for (;; U1 = (rng.nextLong() >>> 1)) {
|
|
994 |
long U2 = (rng.nextLong() >>> 1);
|
|
995 |
// Compute the actual x-coordinate of the randomly chosen point.
|
|
996 |
x = (X[j] * 0x1.0p63) + ((X[j-1] - X[j]) * (double)U1);
|
|
997 |
// Does the point lie below the curve?
|
|
998 |
long Udiff = U2 - U1;
|
|
999 |
if (Udiff >= DoubleZigguratTables.normalConvexMargin) {
|
|
1000 |
break; // The chosen point is way below the curve; accept it.
|
|
1001 |
}
|
|
1002 |
if (Udiff <= -DoubleZigguratTables.normalConcaveMargin) {
|
|
1003 |
continue; // The chosen point is way above the curve; reject it.
|
|
1004 |
}
|
|
1005 |
// Compute the actual y-coordinate of the randomly chosen point.
|
|
1006 |
double y = (Y[j] * 0x1.0p63) + ((Y[j] - Y[j-1]) * (double)U2);
|
|
1007 |
// Now see how that y-coordinate compares to the curve
|
|
1008 |
if (y <= Math.exp(-0.5*x*x)) {
|
|
1009 |
break; // The chosen point is below the curve; accept it.
|
|
1010 |
}
|
|
1011 |
// Otherwise, we reject this sample and have to try again.
|
|
1012 |
}
|
|
1013 |
}
|
|
1014 |
return signBit*x;
|
|
1015 |
}
|
|
1016 |
|
|
1017 |
}
|
|
1018 |
|