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