author | bpb |
Tue, 30 Jul 2013 10:35:06 -0700 | |
changeset 19074 | 84a8d23e8f32 |
parent 18156 | edb590d448c5 |
child 19609 | 108f52a7438f |
permissions | -rw-r--r-- |
2 | 1 |
/* |
14342
8435a30053c1
7197491: update copyright year to match last edit in jdk8 jdk repository
alanb
parents:
10056
diff
changeset
|
2 |
* Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. |
2 | 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 |
|
5506 | 7 |
* published by the Free Software Foundation. Oracle designates this |
2 | 8 |
* particular file as subject to the "Classpath" exception as provided |
5506 | 9 |
* by Oracle in the LICENSE file that accompanied this code. |
2 | 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 |
* |
|
5506 | 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. |
|
2 | 24 |
*/ |
25 |
||
26 |
package java.util; |
|
27 |
import java.io.*; |
|
28 |
import java.util.concurrent.atomic.AtomicLong; |
|
17421
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
29 |
import java.util.stream.DoubleStream; |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
30 |
import java.util.stream.IntStream; |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
31 |
import java.util.stream.LongStream; |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
32 |
|
2 | 33 |
import sun.misc.Unsafe; |
34 |
||
35 |
/** |
|
36 |
* An instance of this class is used to generate a stream of |
|
37 |
* pseudorandom numbers. The class uses a 48-bit seed, which is |
|
38 |
* modified using a linear congruential formula. (See Donald Knuth, |
|
1818 | 39 |
* <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.) |
2 | 40 |
* <p> |
41 |
* If two instances of {@code Random} are created with the same |
|
42 |
* seed, and the same sequence of method calls is made for each, they |
|
43 |
* will generate and return identical sequences of numbers. In order to |
|
44 |
* guarantee this property, particular algorithms are specified for the |
|
45 |
* class {@code Random}. Java implementations must use all the algorithms |
|
46 |
* shown here for the class {@code Random}, for the sake of absolute |
|
47 |
* portability of Java code. However, subclasses of class {@code Random} |
|
48 |
* are permitted to use other algorithms, so long as they adhere to the |
|
49 |
* general contracts for all the methods. |
|
50 |
* <p> |
|
51 |
* The algorithms implemented by class {@code Random} use a |
|
52 |
* {@code protected} utility method that on each invocation can supply |
|
53 |
* up to 32 pseudorandomly generated bits. |
|
54 |
* <p> |
|
55 |
* Many applications will find the method {@link Math#random} simpler to use. |
|
56 |
* |
|
4110 | 57 |
* <p>Instances of {@code java.util.Random} are threadsafe. |
58 |
* However, the concurrent use of the same {@code java.util.Random} |
|
59 |
* instance across threads may encounter contention and consequent |
|
60 |
* poor performance. Consider instead using |
|
61 |
* {@link java.util.concurrent.ThreadLocalRandom} in multithreaded |
|
62 |
* designs. |
|
63 |
* |
|
64 |
* <p>Instances of {@code java.util.Random} are not cryptographically |
|
65 |
* secure. Consider instead using {@link java.security.SecureRandom} to |
|
66 |
* get a cryptographically secure pseudo-random number generator for use |
|
67 |
* by security-sensitive applications. |
|
68 |
* |
|
2 | 69 |
* @author Frank Yellin |
70 |
* @since 1.0 |
|
71 |
*/ |
|
72 |
public |
|
73 |
class Random implements java.io.Serializable { |
|
74 |
/** use serialVersionUID from JDK 1.1 for interoperability */ |
|
75 |
static final long serialVersionUID = 3905348978240129619L; |
|
76 |
||
77 |
/** |
|
78 |
* The internal state associated with this pseudorandom number generator. |
|
79 |
* (The specs for the methods in this class describe the ongoing |
|
80 |
* computation of this value.) |
|
81 |
*/ |
|
82 |
private final AtomicLong seed; |
|
83 |
||
7518 | 84 |
private static final long multiplier = 0x5DEECE66DL; |
85 |
private static final long addend = 0xBL; |
|
86 |
private static final long mask = (1L << 48) - 1; |
|
2 | 87 |
|
88 |
/** |
|
89 |
* Creates a new random number generator. This constructor sets |
|
90 |
* the seed of the random number generator to a value very likely |
|
91 |
* to be distinct from any other invocation of this constructor. |
|
92 |
*/ |
|
5468
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
93 |
public Random() { |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
94 |
this(seedUniquifier() ^ System.nanoTime()); |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
95 |
} |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
96 |
|
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
97 |
private static long seedUniquifier() { |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
98 |
// L'Ecuyer, "Tables of Linear Congruential Generators of |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
99 |
// Different Sizes and Good Lattice Structure", 1999 |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
100 |
for (;;) { |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
101 |
long current = seedUniquifier.get(); |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
102 |
long next = current * 181783497276652981L; |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
103 |
if (seedUniquifier.compareAndSet(current, next)) |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
104 |
return next; |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
105 |
} |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
106 |
} |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
107 |
|
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
108 |
private static final AtomicLong seedUniquifier |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
109 |
= new AtomicLong(8682522807148012L); |
2 | 110 |
|
111 |
/** |
|
112 |
* Creates a new random number generator using a single {@code long} seed. |
|
113 |
* The seed is the initial value of the internal state of the pseudorandom |
|
114 |
* number generator which is maintained by method {@link #next}. |
|
115 |
* |
|
116 |
* <p>The invocation {@code new Random(seed)} is equivalent to: |
|
117 |
* <pre> {@code |
|
118 |
* Random rnd = new Random(); |
|
119 |
* rnd.setSeed(seed);}</pre> |
|
120 |
* |
|
121 |
* @param seed the initial seed |
|
122 |
* @see #setSeed(long) |
|
123 |
*/ |
|
124 |
public Random(long seed) { |
|
10056
7464dc04ae22
7051516: ThreadLocalRandom seed is never initialized so all instances generate the same sequence
dl
parents:
7668
diff
changeset
|
125 |
if (getClass() == Random.class) |
7464dc04ae22
7051516: ThreadLocalRandom seed is never initialized so all instances generate the same sequence
dl
parents:
7668
diff
changeset
|
126 |
this.seed = new AtomicLong(initialScramble(seed)); |
7464dc04ae22
7051516: ThreadLocalRandom seed is never initialized so all instances generate the same sequence
dl
parents:
7668
diff
changeset
|
127 |
else { |
7464dc04ae22
7051516: ThreadLocalRandom seed is never initialized so all instances generate the same sequence
dl
parents:
7668
diff
changeset
|
128 |
// subclass might have overriden setSeed |
7464dc04ae22
7051516: ThreadLocalRandom seed is never initialized so all instances generate the same sequence
dl
parents:
7668
diff
changeset
|
129 |
this.seed = new AtomicLong(); |
7464dc04ae22
7051516: ThreadLocalRandom seed is never initialized so all instances generate the same sequence
dl
parents:
7668
diff
changeset
|
130 |
setSeed(seed); |
7464dc04ae22
7051516: ThreadLocalRandom seed is never initialized so all instances generate the same sequence
dl
parents:
7668
diff
changeset
|
131 |
} |
5468
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
132 |
} |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
133 |
|
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
134 |
private static long initialScramble(long seed) { |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
135 |
return (seed ^ multiplier) & mask; |
2 | 136 |
} |
137 |
||
138 |
/** |
|
139 |
* Sets the seed of this random number generator using a single |
|
140 |
* {@code long} seed. The general contract of {@code setSeed} is |
|
141 |
* that it alters the state of this random number generator object |
|
142 |
* so as to be in exactly the same state as if it had just been |
|
143 |
* created with the argument {@code seed} as a seed. The method |
|
144 |
* {@code setSeed} is implemented by class {@code Random} by |
|
145 |
* atomically updating the seed to |
|
146 |
* <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre> |
|
147 |
* and clearing the {@code haveNextNextGaussian} flag used by {@link |
|
148 |
* #nextGaussian}. |
|
149 |
* |
|
150 |
* <p>The implementation of {@code setSeed} by class {@code Random} |
|
151 |
* happens to use only 48 bits of the given seed. In general, however, |
|
152 |
* an overriding method may use all 64 bits of the {@code long} |
|
153 |
* argument as a seed value. |
|
154 |
* |
|
155 |
* @param seed the initial seed |
|
156 |
*/ |
|
157 |
synchronized public void setSeed(long seed) { |
|
5468
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
158 |
this.seed.set(initialScramble(seed)); |
2 | 159 |
haveNextNextGaussian = false; |
160 |
} |
|
161 |
||
162 |
/** |
|
163 |
* Generates the next pseudorandom number. Subclasses should |
|
164 |
* override this, as this is used by all other methods. |
|
165 |
* |
|
166 |
* <p>The general contract of {@code next} is that it returns an |
|
167 |
* {@code int} value and if the argument {@code bits} is between |
|
168 |
* {@code 1} and {@code 32} (inclusive), then that many low-order |
|
169 |
* bits of the returned value will be (approximately) independently |
|
170 |
* chosen bit values, each of which is (approximately) equally |
|
171 |
* likely to be {@code 0} or {@code 1}. The method {@code next} is |
|
172 |
* implemented by class {@code Random} by atomically updating the seed to |
|
173 |
* <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre> |
|
174 |
* and returning |
|
175 |
* <pre>{@code (int)(seed >>> (48 - bits))}.</pre> |
|
176 |
* |
|
177 |
* This is a linear congruential pseudorandom number generator, as |
|
178 |
* defined by D. H. Lehmer and described by Donald E. Knuth in |
|
179 |
* <i>The Art of Computer Programming,</i> Volume 3: |
|
180 |
* <i>Seminumerical Algorithms</i>, section 3.2.1. |
|
181 |
* |
|
182 |
* @param bits random bits |
|
183 |
* @return the next pseudorandom value from this random number |
|
184 |
* generator's sequence |
|
185 |
* @since 1.1 |
|
186 |
*/ |
|
187 |
protected int next(int bits) { |
|
188 |
long oldseed, nextseed; |
|
189 |
AtomicLong seed = this.seed; |
|
190 |
do { |
|
191 |
oldseed = seed.get(); |
|
192 |
nextseed = (oldseed * multiplier + addend) & mask; |
|
193 |
} while (!seed.compareAndSet(oldseed, nextseed)); |
|
194 |
return (int)(nextseed >>> (48 - bits)); |
|
195 |
} |
|
196 |
||
197 |
/** |
|
198 |
* Generates random bytes and places them into a user-supplied |
|
199 |
* byte array. The number of random bytes produced is equal to |
|
200 |
* the length of the byte array. |
|
201 |
* |
|
202 |
* <p>The method {@code nextBytes} is implemented by class {@code Random} |
|
203 |
* as if by: |
|
204 |
* <pre> {@code |
|
205 |
* public void nextBytes(byte[] bytes) { |
|
206 |
* for (int i = 0; i < bytes.length; ) |
|
207 |
* for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4); |
|
208 |
* n-- > 0; rnd >>= 8) |
|
209 |
* bytes[i++] = (byte)rnd; |
|
210 |
* }}</pre> |
|
211 |
* |
|
212 |
* @param bytes the byte array to fill with random bytes |
|
213 |
* @throws NullPointerException if the byte array is null |
|
214 |
* @since 1.1 |
|
215 |
*/ |
|
216 |
public void nextBytes(byte[] bytes) { |
|
217 |
for (int i = 0, len = bytes.length; i < len; ) |
|
218 |
for (int rnd = nextInt(), |
|
219 |
n = Math.min(len - i, Integer.SIZE/Byte.SIZE); |
|
220 |
n-- > 0; rnd >>= Byte.SIZE) |
|
221 |
bytes[i++] = (byte)rnd; |
|
222 |
} |
|
223 |
||
224 |
/** |
|
225 |
* Returns the next pseudorandom, uniformly distributed {@code int} |
|
226 |
* value from this random number generator's sequence. The general |
|
227 |
* contract of {@code nextInt} is that one {@code int} value is |
|
19074
84a8d23e8f32
8020539: Clean up doclint problems in java.util package, part 2
bpb
parents:
18156
diff
changeset
|
228 |
* pseudorandomly generated and returned. All 2<sup>32</sup> possible |
84a8d23e8f32
8020539: Clean up doclint problems in java.util package, part 2
bpb
parents:
18156
diff
changeset
|
229 |
* {@code int} values are produced with (approximately) equal probability. |
2 | 230 |
* |
231 |
* <p>The method {@code nextInt} is implemented by class {@code Random} |
|
232 |
* as if by: |
|
233 |
* <pre> {@code |
|
234 |
* public int nextInt() { |
|
235 |
* return next(32); |
|
236 |
* }}</pre> |
|
237 |
* |
|
238 |
* @return the next pseudorandom, uniformly distributed {@code int} |
|
239 |
* value from this random number generator's sequence |
|
240 |
*/ |
|
241 |
public int nextInt() { |
|
242 |
return next(32); |
|
243 |
} |
|
244 |
||
245 |
/** |
|
246 |
* Returns a pseudorandom, uniformly distributed {@code int} value |
|
247 |
* between 0 (inclusive) and the specified value (exclusive), drawn from |
|
248 |
* this random number generator's sequence. The general contract of |
|
249 |
* {@code nextInt} is that one {@code int} value in the specified range |
|
250 |
* is pseudorandomly generated and returned. All {@code n} possible |
|
251 |
* {@code int} values are produced with (approximately) equal |
|
252 |
* probability. The method {@code nextInt(int n)} is implemented by |
|
253 |
* class {@code Random} as if by: |
|
254 |
* <pre> {@code |
|
255 |
* public int nextInt(int n) { |
|
256 |
* if (n <= 0) |
|
257 |
* throw new IllegalArgumentException("n must be positive"); |
|
258 |
* |
|
259 |
* if ((n & -n) == n) // i.e., n is a power of 2 |
|
260 |
* return (int)((n * (long)next(31)) >> 31); |
|
261 |
* |
|
262 |
* int bits, val; |
|
263 |
* do { |
|
264 |
* bits = next(31); |
|
265 |
* val = bits % n; |
|
266 |
* } while (bits - val + (n-1) < 0); |
|
267 |
* return val; |
|
268 |
* }}</pre> |
|
269 |
* |
|
270 |
* <p>The hedge "approximately" is used in the foregoing description only |
|
271 |
* because the next method is only approximately an unbiased source of |
|
272 |
* independently chosen bits. If it were a perfect source of randomly |
|
273 |
* chosen bits, then the algorithm shown would choose {@code int} |
|
274 |
* values from the stated range with perfect uniformity. |
|
275 |
* <p> |
|
276 |
* The algorithm is slightly tricky. It rejects values that would result |
|
277 |
* in an uneven distribution (due to the fact that 2^31 is not divisible |
|
278 |
* by n). The probability of a value being rejected depends on n. The |
|
279 |
* worst case is n=2^30+1, for which the probability of a reject is 1/2, |
|
280 |
* and the expected number of iterations before the loop terminates is 2. |
|
281 |
* <p> |
|
282 |
* The algorithm treats the case where n is a power of two specially: it |
|
283 |
* returns the correct number of high-order bits from the underlying |
|
284 |
* pseudo-random number generator. In the absence of special treatment, |
|
285 |
* the correct number of <i>low-order</i> bits would be returned. Linear |
|
286 |
* congruential pseudo-random number generators such as the one |
|
287 |
* implemented by this class are known to have short periods in the |
|
288 |
* sequence of values of their low-order bits. Thus, this special case |
|
289 |
* greatly increases the length of the sequence of values returned by |
|
290 |
* successive calls to this method if n is a small power of two. |
|
291 |
* |
|
292 |
* @param n the bound on the random number to be returned. Must be |
|
293 |
* positive. |
|
294 |
* @return the next pseudorandom, uniformly distributed {@code int} |
|
295 |
* value between {@code 0} (inclusive) and {@code n} (exclusive) |
|
296 |
* from this random number generator's sequence |
|
7518 | 297 |
* @throws IllegalArgumentException if n is not positive |
2 | 298 |
* @since 1.2 |
299 |
*/ |
|
300 |
||
301 |
public int nextInt(int n) { |
|
302 |
if (n <= 0) |
|
303 |
throw new IllegalArgumentException("n must be positive"); |
|
304 |
||
305 |
if ((n & -n) == n) // i.e., n is a power of 2 |
|
306 |
return (int)((n * (long)next(31)) >> 31); |
|
307 |
||
308 |
int bits, val; |
|
309 |
do { |
|
310 |
bits = next(31); |
|
311 |
val = bits % n; |
|
312 |
} while (bits - val + (n-1) < 0); |
|
313 |
return val; |
|
314 |
} |
|
315 |
||
316 |
/** |
|
317 |
* Returns the next pseudorandom, uniformly distributed {@code long} |
|
318 |
* value from this random number generator's sequence. The general |
|
319 |
* contract of {@code nextLong} is that one {@code long} value is |
|
320 |
* pseudorandomly generated and returned. |
|
321 |
* |
|
322 |
* <p>The method {@code nextLong} is implemented by class {@code Random} |
|
323 |
* as if by: |
|
324 |
* <pre> {@code |
|
325 |
* public long nextLong() { |
|
326 |
* return ((long)next(32) << 32) + next(32); |
|
327 |
* }}</pre> |
|
328 |
* |
|
329 |
* Because class {@code Random} uses a seed with only 48 bits, |
|
330 |
* this algorithm will not return all possible {@code long} values. |
|
331 |
* |
|
332 |
* @return the next pseudorandom, uniformly distributed {@code long} |
|
333 |
* value from this random number generator's sequence |
|
334 |
*/ |
|
335 |
public long nextLong() { |
|
336 |
// it's okay that the bottom word remains signed. |
|
337 |
return ((long)(next(32)) << 32) + next(32); |
|
338 |
} |
|
339 |
||
340 |
/** |
|
341 |
* Returns the next pseudorandom, uniformly distributed |
|
342 |
* {@code boolean} value from this random number generator's |
|
343 |
* sequence. The general contract of {@code nextBoolean} is that one |
|
344 |
* {@code boolean} value is pseudorandomly generated and returned. The |
|
345 |
* values {@code true} and {@code false} are produced with |
|
346 |
* (approximately) equal probability. |
|
347 |
* |
|
348 |
* <p>The method {@code nextBoolean} is implemented by class {@code Random} |
|
349 |
* as if by: |
|
350 |
* <pre> {@code |
|
351 |
* public boolean nextBoolean() { |
|
352 |
* return next(1) != 0; |
|
353 |
* }}</pre> |
|
354 |
* |
|
355 |
* @return the next pseudorandom, uniformly distributed |
|
356 |
* {@code boolean} value from this random number generator's |
|
357 |
* sequence |
|
358 |
* @since 1.2 |
|
359 |
*/ |
|
360 |
public boolean nextBoolean() { |
|
361 |
return next(1) != 0; |
|
362 |
} |
|
363 |
||
364 |
/** |
|
365 |
* Returns the next pseudorandom, uniformly distributed {@code float} |
|
366 |
* value between {@code 0.0} and {@code 1.0} from this random |
|
367 |
* number generator's sequence. |
|
368 |
* |
|
369 |
* <p>The general contract of {@code nextFloat} is that one |
|
370 |
* {@code float} value, chosen (approximately) uniformly from the |
|
371 |
* range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is |
|
19074
84a8d23e8f32
8020539: Clean up doclint problems in java.util package, part 2
bpb
parents:
18156
diff
changeset
|
372 |
* pseudorandomly generated and returned. All 2<sup>24</sup> possible |
84a8d23e8f32
8020539: Clean up doclint problems in java.util package, part 2
bpb
parents:
18156
diff
changeset
|
373 |
* {@code float} values of the form <i>m x </i>2<sup>-24</sup>, |
84a8d23e8f32
8020539: Clean up doclint problems in java.util package, part 2
bpb
parents:
18156
diff
changeset
|
374 |
* where <i>m</i> is a positive integer less than 2<sup>24</sup>, are |
2 | 375 |
* produced with (approximately) equal probability. |
376 |
* |
|
377 |
* <p>The method {@code nextFloat} is implemented by class {@code Random} |
|
378 |
* as if by: |
|
379 |
* <pre> {@code |
|
380 |
* public float nextFloat() { |
|
381 |
* return next(24) / ((float)(1 << 24)); |
|
382 |
* }}</pre> |
|
383 |
* |
|
384 |
* <p>The hedge "approximately" is used in the foregoing description only |
|
385 |
* because the next method is only approximately an unbiased source of |
|
386 |
* independently chosen bits. If it were a perfect source of randomly |
|
387 |
* chosen bits, then the algorithm shown would choose {@code float} |
|
388 |
* values from the stated range with perfect uniformity.<p> |
|
389 |
* [In early versions of Java, the result was incorrectly calculated as: |
|
390 |
* <pre> {@code |
|
391 |
* return next(30) / ((float)(1 << 30));}</pre> |
|
392 |
* This might seem to be equivalent, if not better, but in fact it |
|
393 |
* introduced a slight nonuniformity because of the bias in the rounding |
|
394 |
* of floating-point numbers: it was slightly more likely that the |
|
395 |
* low-order bit of the significand would be 0 than that it would be 1.] |
|
396 |
* |
|
397 |
* @return the next pseudorandom, uniformly distributed {@code float} |
|
398 |
* value between {@code 0.0} and {@code 1.0} from this |
|
399 |
* random number generator's sequence |
|
400 |
*/ |
|
401 |
public float nextFloat() { |
|
402 |
return next(24) / ((float)(1 << 24)); |
|
403 |
} |
|
404 |
||
405 |
/** |
|
406 |
* Returns the next pseudorandom, uniformly distributed |
|
407 |
* {@code double} value between {@code 0.0} and |
|
408 |
* {@code 1.0} from this random number generator's sequence. |
|
409 |
* |
|
410 |
* <p>The general contract of {@code nextDouble} is that one |
|
411 |
* {@code double} value, chosen (approximately) uniformly from the |
|
412 |
* range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is |
|
413 |
* pseudorandomly generated and returned. |
|
414 |
* |
|
415 |
* <p>The method {@code nextDouble} is implemented by class {@code Random} |
|
416 |
* as if by: |
|
417 |
* <pre> {@code |
|
418 |
* public double nextDouble() { |
|
419 |
* return (((long)next(26) << 27) + next(27)) |
|
420 |
* / (double)(1L << 53); |
|
421 |
* }}</pre> |
|
422 |
* |
|
423 |
* <p>The hedge "approximately" is used in the foregoing description only |
|
424 |
* because the {@code next} method is only approximately an unbiased |
|
425 |
* source of independently chosen bits. If it were a perfect source of |
|
426 |
* randomly chosen bits, then the algorithm shown would choose |
|
427 |
* {@code double} values from the stated range with perfect uniformity. |
|
428 |
* <p>[In early versions of Java, the result was incorrectly calculated as: |
|
429 |
* <pre> {@code |
|
430 |
* return (((long)next(27) << 27) + next(27)) |
|
431 |
* / (double)(1L << 54);}</pre> |
|
432 |
* This might seem to be equivalent, if not better, but in fact it |
|
433 |
* introduced a large nonuniformity because of the bias in the rounding |
|
434 |
* of floating-point numbers: it was three times as likely that the |
|
435 |
* low-order bit of the significand would be 0 than that it would be 1! |
|
436 |
* This nonuniformity probably doesn't matter much in practice, but we |
|
437 |
* strive for perfection.] |
|
438 |
* |
|
439 |
* @return the next pseudorandom, uniformly distributed {@code double} |
|
440 |
* value between {@code 0.0} and {@code 1.0} from this |
|
441 |
* random number generator's sequence |
|
442 |
* @see Math#random |
|
443 |
*/ |
|
444 |
public double nextDouble() { |
|
445 |
return (((long)(next(26)) << 27) + next(27)) |
|
446 |
/ (double)(1L << 53); |
|
447 |
} |
|
448 |
||
449 |
private double nextNextGaussian; |
|
450 |
private boolean haveNextNextGaussian = false; |
|
451 |
||
452 |
/** |
|
453 |
* Returns the next pseudorandom, Gaussian ("normally") distributed |
|
454 |
* {@code double} value with mean {@code 0.0} and standard |
|
455 |
* deviation {@code 1.0} from this random number generator's sequence. |
|
456 |
* <p> |
|
457 |
* The general contract of {@code nextGaussian} is that one |
|
458 |
* {@code double} value, chosen from (approximately) the usual |
|
459 |
* normal distribution with mean {@code 0.0} and standard deviation |
|
460 |
* {@code 1.0}, is pseudorandomly generated and returned. |
|
461 |
* |
|
462 |
* <p>The method {@code nextGaussian} is implemented by class |
|
463 |
* {@code Random} as if by a threadsafe version of the following: |
|
464 |
* <pre> {@code |
|
465 |
* private double nextNextGaussian; |
|
466 |
* private boolean haveNextNextGaussian = false; |
|
467 |
* |
|
468 |
* public double nextGaussian() { |
|
469 |
* if (haveNextNextGaussian) { |
|
470 |
* haveNextNextGaussian = false; |
|
471 |
* return nextNextGaussian; |
|
472 |
* } else { |
|
473 |
* double v1, v2, s; |
|
474 |
* do { |
|
475 |
* v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0 |
|
476 |
* v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0 |
|
477 |
* s = v1 * v1 + v2 * v2; |
|
478 |
* } while (s >= 1 || s == 0); |
|
479 |
* double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s); |
|
480 |
* nextNextGaussian = v2 * multiplier; |
|
481 |
* haveNextNextGaussian = true; |
|
482 |
* return v1 * multiplier; |
|
483 |
* } |
|
484 |
* }}</pre> |
|
485 |
* This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and |
|
486 |
* G. Marsaglia, as described by Donald E. Knuth in <i>The Art of |
|
487 |
* Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>, |
|
488 |
* section 3.4.1, subsection C, algorithm P. Note that it generates two |
|
489 |
* independent values at the cost of only one call to {@code StrictMath.log} |
|
490 |
* and one call to {@code StrictMath.sqrt}. |
|
491 |
* |
|
492 |
* @return the next pseudorandom, Gaussian ("normally") distributed |
|
493 |
* {@code double} value with mean {@code 0.0} and |
|
494 |
* standard deviation {@code 1.0} from this random number |
|
495 |
* generator's sequence |
|
496 |
*/ |
|
497 |
synchronized public double nextGaussian() { |
|
498 |
// See Knuth, ACP, Section 3.4.1 Algorithm C. |
|
499 |
if (haveNextNextGaussian) { |
|
500 |
haveNextNextGaussian = false; |
|
501 |
return nextNextGaussian; |
|
502 |
} else { |
|
503 |
double v1, v2, s; |
|
504 |
do { |
|
505 |
v1 = 2 * nextDouble() - 1; // between -1 and 1 |
|
506 |
v2 = 2 * nextDouble() - 1; // between -1 and 1 |
|
507 |
s = v1 * v1 + v2 * v2; |
|
508 |
} while (s >= 1 || s == 0); |
|
509 |
double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s); |
|
510 |
nextNextGaussian = v2 * multiplier; |
|
511 |
haveNextNextGaussian = true; |
|
512 |
return v1 * multiplier; |
|
513 |
} |
|
514 |
} |
|
515 |
||
516 |
/** |
|
17421
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
517 |
* Returns a stream of pseudorandom, uniformly distributed |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
518 |
* {@code integer} values from this random number generator's |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
519 |
* sequence. Values are obtained as needed by calling |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
520 |
* {@link #nextInt()}. |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
521 |
* |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
522 |
* @return an infinite stream of {@code integer} values |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
523 |
* @since 1.8 |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
524 |
*/ |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
525 |
public IntStream ints() { |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
526 |
return IntStream.generate(this::nextInt); |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
527 |
} |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
528 |
|
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
529 |
/** |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
530 |
* Returns a stream of pseudorandom, uniformly distributed |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
531 |
* {@code long} values from this random number generator's |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
532 |
* sequence. Values are obtained as needed by calling |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
533 |
* {@link #nextLong()}. |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
534 |
* |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
535 |
* @return an infinite stream of {@code long} values |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
536 |
* @since 1.8 |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
537 |
*/ |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
538 |
public LongStream longs() { |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
539 |
return LongStream.generate(this::nextLong); |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
540 |
} |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
541 |
|
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
542 |
/** |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
543 |
* Returns a stream of pseudorandom, uniformly distributed |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
544 |
* {@code double} values between {@code 0.0} and {@code 1.0} |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
545 |
* from this random number generator's sequence. Values are |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
546 |
* obtained as needed by calling {@link #nextDouble()}. |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
547 |
* |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
548 |
* @return an infinite stream of {@code double} values |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
549 |
* @since 1.8 |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
550 |
*/ |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
551 |
public DoubleStream doubles() { |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
552 |
return DoubleStream.generate(this::nextDouble); |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
553 |
} |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
554 |
|
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
555 |
/** |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
556 |
* Returns a stream of pseudorandom, Gaussian ("normally") |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
557 |
* distributed {@code double} values with mean {@code 0.0} |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
558 |
* and standard deviation {@code 1.0} from this random number |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
559 |
* generator's sequence. Values are obtained as needed by |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
560 |
* calling {@link #nextGaussian()}. |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
561 |
* |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
562 |
* @return an infinite stream of {@code double} values |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
563 |
* @since 1.8 |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
564 |
*/ |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
565 |
public DoubleStream gaussians() { |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
566 |
return DoubleStream.generate(this::nextGaussian); |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
567 |
} |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
568 |
|
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
569 |
/** |
2 | 570 |
* Serializable fields for Random. |
571 |
* |
|
572 |
* @serialField seed long |
|
573 |
* seed for random computations |
|
574 |
* @serialField nextNextGaussian double |
|
575 |
* next Gaussian to be returned |
|
576 |
* @serialField haveNextNextGaussian boolean |
|
577 |
* nextNextGaussian is valid |
|
578 |
*/ |
|
579 |
private static final ObjectStreamField[] serialPersistentFields = { |
|
580 |
new ObjectStreamField("seed", Long.TYPE), |
|
581 |
new ObjectStreamField("nextNextGaussian", Double.TYPE), |
|
582 |
new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE) |
|
583 |
}; |
|
584 |
||
585 |
/** |
|
586 |
* Reconstitute the {@code Random} instance from a stream (that is, |
|
587 |
* deserialize it). |
|
588 |
*/ |
|
589 |
private void readObject(java.io.ObjectInputStream s) |
|
590 |
throws java.io.IOException, ClassNotFoundException { |
|
591 |
||
592 |
ObjectInputStream.GetField fields = s.readFields(); |
|
593 |
||
594 |
// The seed is read in as {@code long} for |
|
595 |
// historical reasons, but it is converted to an AtomicLong. |
|
51 | 596 |
long seedVal = fields.get("seed", -1L); |
2 | 597 |
if (seedVal < 0) |
598 |
throw new java.io.StreamCorruptedException( |
|
599 |
"Random: invalid seed"); |
|
600 |
resetSeed(seedVal); |
|
601 |
nextNextGaussian = fields.get("nextNextGaussian", 0.0); |
|
602 |
haveNextNextGaussian = fields.get("haveNextNextGaussian", false); |
|
603 |
} |
|
604 |
||
605 |
/** |
|
606 |
* Save the {@code Random} instance to a stream. |
|
607 |
*/ |
|
608 |
synchronized private void writeObject(ObjectOutputStream s) |
|
609 |
throws IOException { |
|
610 |
||
611 |
// set the values of the Serializable fields |
|
612 |
ObjectOutputStream.PutField fields = s.putFields(); |
|
613 |
||
614 |
// The seed is serialized as a long for historical reasons. |
|
615 |
fields.put("seed", seed.get()); |
|
616 |
fields.put("nextNextGaussian", nextNextGaussian); |
|
617 |
fields.put("haveNextNextGaussian", haveNextNextGaussian); |
|
618 |
||
619 |
// save them |
|
620 |
s.writeFields(); |
|
621 |
} |
|
622 |
||
623 |
// Support for resetting seed while deserializing |
|
624 |
private static final Unsafe unsafe = Unsafe.getUnsafe(); |
|
625 |
private static final long seedOffset; |
|
626 |
static { |
|
627 |
try { |
|
628 |
seedOffset = unsafe.objectFieldOffset |
|
629 |
(Random.class.getDeclaredField("seed")); |
|
630 |
} catch (Exception ex) { throw new Error(ex); } |
|
631 |
} |
|
632 |
private void resetSeed(long seedVal) { |
|
633 |
unsafe.putObjectVolatile(this, seedOffset, new AtomicLong(seedVal)); |
|
634 |
} |
|
635 |
} |