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