author | jlaskey |
Thu, 14 Nov 2019 12:39:49 -0400 | |
branch | JDK-8193209-branch |
changeset 59086 | 214afc7a1e02 |
parent 57956 | e0b8b019d2f5 |
permissions | -rw-r--r-- |
2 | 1 |
/* |
57956
e0b8b019d2f5
8229997: Apply java.io.Serial annotations in java.base
darcy
parents:
52220
diff
changeset
|
2 |
* Copyright (c) 1995, 2019, 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; |
|
59086 | 27 |
|
2 | 28 |
import java.io.*; |
59086 | 29 |
import java.math.BigInteger; |
30 |
import java.util.Spliterator; |
|
2 | 31 |
import java.util.concurrent.atomic.AtomicLong; |
19609
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
32 |
import java.util.function.DoubleConsumer; |
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
33 |
import java.util.function.IntConsumer; |
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
34 |
import java.util.function.LongConsumer; |
59086 | 35 |
import java.util.random.RandomGenerator; |
36 |
import java.util.random.RandomSupport; |
|
37 |
import java.util.random.RandomSupport.AbstractSpliteratorGenerator; |
|
38 |
import java.util.random.RandomSupport.RandomSpliterator; |
|
17421
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
39 |
import java.util.stream.DoubleStream; |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
40 |
import java.util.stream.IntStream; |
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
41 |
import java.util.stream.LongStream; |
19609
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
42 |
import java.util.stream.StreamSupport; |
17421
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
43 |
|
33674
566777f73c32
8140606: Update library code to use internal Unsafe
chegar
parents:
32649
diff
changeset
|
44 |
import jdk.internal.misc.Unsafe; |
2 | 45 |
|
46 |
/** |
|
47 |
* An instance of this class is used to generate a stream of |
|
48 |
* pseudorandom numbers. The class uses a 48-bit seed, which is |
|
49 |
* modified using a linear congruential formula. (See Donald Knuth, |
|
1818 | 50 |
* <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.) |
2 | 51 |
* <p> |
52 |
* If two instances of {@code Random} are created with the same |
|
53 |
* seed, and the same sequence of method calls is made for each, they |
|
54 |
* will generate and return identical sequences of numbers. In order to |
|
55 |
* guarantee this property, particular algorithms are specified for the |
|
56 |
* class {@code Random}. Java implementations must use all the algorithms |
|
57 |
* shown here for the class {@code Random}, for the sake of absolute |
|
58 |
* portability of Java code. However, subclasses of class {@code Random} |
|
59 |
* are permitted to use other algorithms, so long as they adhere to the |
|
60 |
* general contracts for all the methods. |
|
61 |
* <p> |
|
62 |
* The algorithms implemented by class {@code Random} use a |
|
63 |
* {@code protected} utility method that on each invocation can supply |
|
64 |
* up to 32 pseudorandomly generated bits. |
|
65 |
* <p> |
|
66 |
* Many applications will find the method {@link Math#random} simpler to use. |
|
67 |
* |
|
4110 | 68 |
* <p>Instances of {@code java.util.Random} are threadsafe. |
69 |
* However, the concurrent use of the same {@code java.util.Random} |
|
70 |
* instance across threads may encounter contention and consequent |
|
71 |
* poor performance. Consider instead using |
|
72 |
* {@link java.util.concurrent.ThreadLocalRandom} in multithreaded |
|
73 |
* designs. |
|
74 |
* |
|
75 |
* <p>Instances of {@code java.util.Random} are not cryptographically |
|
76 |
* secure. Consider instead using {@link java.security.SecureRandom} to |
|
77 |
* get a cryptographically secure pseudo-random number generator for use |
|
78 |
* by security-sensitive applications. |
|
79 |
* |
|
2 | 80 |
* @author Frank Yellin |
81 |
* @since 1.0 |
|
82 |
*/ |
|
83 |
public |
|
59086 | 84 |
class Random extends AbstractSpliteratorGenerator implements java.io.Serializable { |
2 | 85 |
/** use serialVersionUID from JDK 1.1 for interoperability */ |
57956
e0b8b019d2f5
8229997: Apply java.io.Serial annotations in java.base
darcy
parents:
52220
diff
changeset
|
86 |
@java.io.Serial |
2 | 87 |
static final long serialVersionUID = 3905348978240129619L; |
88 |
||
89 |
/** |
|
90 |
* The internal state associated with this pseudorandom number generator. |
|
91 |
* (The specs for the methods in this class describe the ongoing |
|
92 |
* computation of this value.) |
|
93 |
*/ |
|
94 |
private final AtomicLong seed; |
|
95 |
||
7518 | 96 |
private static final long multiplier = 0x5DEECE66DL; |
97 |
private static final long addend = 0xBL; |
|
98 |
private static final long mask = (1L << 48) - 1; |
|
2 | 99 |
|
20540 | 100 |
private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53) |
19609
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
101 |
|
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
102 |
// IllegalArgumentException messages |
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
103 |
static final String BadBound = "bound must be positive"; |
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
104 |
static final String BadRange = "bound must be greater than origin"; |
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
105 |
static final String BadSize = "size must be non-negative"; |
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
106 |
|
2 | 107 |
/** |
108 |
* Creates a new random number generator. This constructor sets |
|
109 |
* the seed of the random number generator to a value very likely |
|
110 |
* to be distinct from any other invocation of this constructor. |
|
111 |
*/ |
|
5468
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
112 |
public Random() { |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
113 |
this(seedUniquifier() ^ System.nanoTime()); |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
114 |
} |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
115 |
|
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
116 |
private static long seedUniquifier() { |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
117 |
// L'Ecuyer, "Tables of Linear Congruential Generators of |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
118 |
// Different Sizes and Good Lattice Structure", 1999 |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
119 |
for (;;) { |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
120 |
long current = seedUniquifier.get(); |
49954 | 121 |
long next = current * 1181783497276652981L; |
5468
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
122 |
if (seedUniquifier.compareAndSet(current, next)) |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
123 |
return next; |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
124 |
} |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
125 |
} |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
126 |
|
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
127 |
private static final AtomicLong seedUniquifier |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
128 |
= new AtomicLong(8682522807148012L); |
2 | 129 |
|
130 |
/** |
|
131 |
* Creates a new random number generator using a single {@code long} seed. |
|
132 |
* The seed is the initial value of the internal state of the pseudorandom |
|
133 |
* number generator which is maintained by method {@link #next}. |
|
134 |
* |
|
135 |
* <p>The invocation {@code new Random(seed)} is equivalent to: |
|
136 |
* <pre> {@code |
|
137 |
* Random rnd = new Random(); |
|
138 |
* rnd.setSeed(seed);}</pre> |
|
139 |
* |
|
140 |
* @param seed the initial seed |
|
141 |
* @see #setSeed(long) |
|
142 |
*/ |
|
143 |
public Random(long seed) { |
|
10056
7464dc04ae22
7051516: ThreadLocalRandom seed is never initialized so all instances generate the same sequence
dl
parents:
7668
diff
changeset
|
144 |
if (getClass() == Random.class) |
7464dc04ae22
7051516: ThreadLocalRandom seed is never initialized so all instances generate the same sequence
dl
parents:
7668
diff
changeset
|
145 |
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
|
146 |
else { |
51759
ac6e9a2ebc04
8210786: Typo s/overriden/overridden/ in several places
igerasim
parents:
49954
diff
changeset
|
147 |
// subclass might have overridden setSeed |
10056
7464dc04ae22
7051516: ThreadLocalRandom seed is never initialized so all instances generate the same sequence
dl
parents:
7668
diff
changeset
|
148 |
this.seed = new AtomicLong(); |
7464dc04ae22
7051516: ThreadLocalRandom seed is never initialized so all instances generate the same sequence
dl
parents:
7668
diff
changeset
|
149 |
setSeed(seed); |
7464dc04ae22
7051516: ThreadLocalRandom seed is never initialized so all instances generate the same sequence
dl
parents:
7668
diff
changeset
|
150 |
} |
5468
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
151 |
} |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
152 |
|
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
153 |
private static long initialScramble(long seed) { |
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
154 |
return (seed ^ multiplier) & mask; |
2 | 155 |
} |
156 |
||
157 |
/** |
|
158 |
* Sets the seed of this random number generator using a single |
|
159 |
* {@code long} seed. The general contract of {@code setSeed} is |
|
160 |
* that it alters the state of this random number generator object |
|
161 |
* so as to be in exactly the same state as if it had just been |
|
162 |
* created with the argument {@code seed} as a seed. The method |
|
163 |
* {@code setSeed} is implemented by class {@code Random} by |
|
164 |
* atomically updating the seed to |
|
165 |
* <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre> |
|
166 |
* and clearing the {@code haveNextNextGaussian} flag used by {@link |
|
167 |
* #nextGaussian}. |
|
168 |
* |
|
169 |
* <p>The implementation of {@code setSeed} by class {@code Random} |
|
170 |
* happens to use only 48 bits of the given seed. In general, however, |
|
171 |
* an overriding method may use all 64 bits of the {@code long} |
|
172 |
* argument as a seed value. |
|
173 |
* |
|
174 |
* @param seed the initial seed |
|
175 |
*/ |
|
32649
2ee9017c7597
8136583: Core libraries should use blessed modifier order
martin
parents:
25859
diff
changeset
|
176 |
public synchronized void setSeed(long seed) { |
5468
c9aa7dfb4f78
6937857: Concurrent calls to new Random() not random enough
martin
parents:
4110
diff
changeset
|
177 |
this.seed.set(initialScramble(seed)); |
2 | 178 |
haveNextNextGaussian = false; |
179 |
} |
|
180 |
||
181 |
/** |
|
182 |
* Generates the next pseudorandom number. Subclasses should |
|
183 |
* override this, as this is used by all other methods. |
|
184 |
* |
|
185 |
* <p>The general contract of {@code next} is that it returns an |
|
186 |
* {@code int} value and if the argument {@code bits} is between |
|
187 |
* {@code 1} and {@code 32} (inclusive), then that many low-order |
|
188 |
* bits of the returned value will be (approximately) independently |
|
189 |
* chosen bit values, each of which is (approximately) equally |
|
190 |
* likely to be {@code 0} or {@code 1}. The method {@code next} is |
|
191 |
* implemented by class {@code Random} by atomically updating the seed to |
|
192 |
* <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre> |
|
193 |
* and returning |
|
194 |
* <pre>{@code (int)(seed >>> (48 - bits))}.</pre> |
|
195 |
* |
|
196 |
* This is a linear congruential pseudorandom number generator, as |
|
197 |
* defined by D. H. Lehmer and described by Donald E. Knuth in |
|
43003
b1c1a42602d6
8164923: Error in the documentation for java.lang.Random
rriggs
parents:
33674
diff
changeset
|
198 |
* <i>The Art of Computer Programming,</i> Volume 2: |
2 | 199 |
* <i>Seminumerical Algorithms</i>, section 3.2.1. |
200 |
* |
|
201 |
* @param bits random bits |
|
202 |
* @return the next pseudorandom value from this random number |
|
203 |
* generator's sequence |
|
204 |
* @since 1.1 |
|
205 |
*/ |
|
206 |
protected int next(int bits) { |
|
207 |
long oldseed, nextseed; |
|
208 |
AtomicLong seed = this.seed; |
|
209 |
do { |
|
210 |
oldseed = seed.get(); |
|
211 |
nextseed = (oldseed * multiplier + addend) & mask; |
|
212 |
} while (!seed.compareAndSet(oldseed, nextseed)); |
|
213 |
return (int)(nextseed >>> (48 - bits)); |
|
214 |
} |
|
215 |
||
59086 | 216 |
/* |
217 |
* Period of Random is 2**48 |
|
218 |
*/ |
|
219 |
private static final BigInteger PERIOD = BigInteger.valueOf(1L<<48); |
|
220 |
||
221 |
/** |
|
222 |
* Returns the period of this random number generator. |
|
223 |
* |
|
224 |
* @return the period of this random number generator. |
|
225 |
*/ |
|
226 |
public BigInteger period() { |
|
227 |
return PERIOD; |
|
228 |
} |
|
229 |
||
2 | 230 |
/** |
231 |
* Generates random bytes and places them into a user-supplied |
|
232 |
* byte array. The number of random bytes produced is equal to |
|
233 |
* the length of the byte array. |
|
234 |
* |
|
235 |
* <p>The method {@code nextBytes} is implemented by class {@code Random} |
|
236 |
* as if by: |
|
237 |
* <pre> {@code |
|
238 |
* public void nextBytes(byte[] bytes) { |
|
239 |
* for (int i = 0; i < bytes.length; ) |
|
240 |
* for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4); |
|
241 |
* n-- > 0; rnd >>= 8) |
|
242 |
* bytes[i++] = (byte)rnd; |
|
243 |
* }}</pre> |
|
244 |
* |
|
245 |
* @param bytes the byte array to fill with random bytes |
|
246 |
* @throws NullPointerException if the byte array is null |
|
247 |
* @since 1.1 |
|
248 |
*/ |
|
249 |
public void nextBytes(byte[] bytes) { |
|
250 |
for (int i = 0, len = bytes.length; i < len; ) |
|
251 |
for (int rnd = nextInt(), |
|
252 |
n = Math.min(len - i, Integer.SIZE/Byte.SIZE); |
|
253 |
n-- > 0; rnd >>= Byte.SIZE) |
|
254 |
bytes[i++] = (byte)rnd; |
|
255 |
} |
|
256 |
||
257 |
/** |
|
258 |
* Returns the next pseudorandom, uniformly distributed {@code int} |
|
259 |
* value from this random number generator's sequence. The general |
|
260 |
* 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
|
261 |
* 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
|
262 |
* {@code int} values are produced with (approximately) equal probability. |
2 | 263 |
* |
264 |
* <p>The method {@code nextInt} is implemented by class {@code Random} |
|
265 |
* as if by: |
|
266 |
* <pre> {@code |
|
267 |
* public int nextInt() { |
|
268 |
* return next(32); |
|
269 |
* }}</pre> |
|
270 |
* |
|
271 |
* @return the next pseudorandom, uniformly distributed {@code int} |
|
272 |
* value from this random number generator's sequence |
|
273 |
*/ |
|
274 |
public int nextInt() { |
|
275 |
return next(32); |
|
276 |
} |
|
277 |
||
278 |
/** |
|
59086 | 279 |
* Returns a pseudorandom {@code int} value between zero (inclusive) |
280 |
* and the specified bound (exclusive). |
|
2 | 281 |
* |
19609
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
282 |
* @param bound the upper bound (exclusive). Must be positive. |
59086 | 283 |
* @return a pseudorandom {@code int} value between zero |
284 |
* (inclusive) and the bound (exclusive) |
|
285 |
* @throws IllegalArgumentException if {@code bound} is not positive |
|
2 | 286 |
*/ |
19609
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
287 |
public int nextInt(int bound) { |
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
288 |
if (bound <= 0) |
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
289 |
throw new IllegalArgumentException(BadBound); |
59086 | 290 |
// Specialize internalNextInt for origin 0 |
291 |
int r = nextInt(); |
|
19609
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
292 |
int m = bound - 1; |
59086 | 293 |
if ((bound & m) == 0) // power of two |
294 |
r &= m; |
|
295 |
else { // reject over-represented candidates |
|
296 |
for (int u = r >>> 1; |
|
297 |
u + m - (r = u % bound) < 0; |
|
298 |
u = nextInt() >>> 1) |
|
19609
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
299 |
; |
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
300 |
} |
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
301 |
return r; |
2 | 302 |
} |
303 |
||
304 |
/** |
|
305 |
* Returns the next pseudorandom, uniformly distributed {@code long} |
|
306 |
* value from this random number generator's sequence. The general |
|
307 |
* contract of {@code nextLong} is that one {@code long} value is |
|
308 |
* pseudorandomly generated and returned. |
|
309 |
* |
|
310 |
* <p>The method {@code nextLong} is implemented by class {@code Random} |
|
311 |
* as if by: |
|
312 |
* <pre> {@code |
|
313 |
* public long nextLong() { |
|
314 |
* return ((long)next(32) << 32) + next(32); |
|
315 |
* }}</pre> |
|
316 |
* |
|
317 |
* Because class {@code Random} uses a seed with only 48 bits, |
|
318 |
* this algorithm will not return all possible {@code long} values. |
|
319 |
* |
|
320 |
* @return the next pseudorandom, uniformly distributed {@code long} |
|
321 |
* value from this random number generator's sequence |
|
322 |
*/ |
|
323 |
public long nextLong() { |
|
324 |
// it's okay that the bottom word remains signed. |
|
325 |
return ((long)(next(32)) << 32) + next(32); |
|
326 |
} |
|
327 |
||
328 |
/** |
|
329 |
* Returns the next pseudorandom, uniformly distributed |
|
330 |
* {@code boolean} value from this random number generator's |
|
331 |
* sequence. The general contract of {@code nextBoolean} is that one |
|
332 |
* {@code boolean} value is pseudorandomly generated and returned. The |
|
333 |
* values {@code true} and {@code false} are produced with |
|
334 |
* (approximately) equal probability. |
|
335 |
* |
|
336 |
* <p>The method {@code nextBoolean} is implemented by class {@code Random} |
|
337 |
* as if by: |
|
338 |
* <pre> {@code |
|
339 |
* public boolean nextBoolean() { |
|
340 |
* return next(1) != 0; |
|
341 |
* }}</pre> |
|
342 |
* |
|
343 |
* @return the next pseudorandom, uniformly distributed |
|
344 |
* {@code boolean} value from this random number generator's |
|
345 |
* sequence |
|
346 |
* @since 1.2 |
|
347 |
*/ |
|
348 |
public boolean nextBoolean() { |
|
349 |
return next(1) != 0; |
|
350 |
} |
|
351 |
||
352 |
/** |
|
353 |
* Returns the next pseudorandom, uniformly distributed {@code float} |
|
354 |
* value between {@code 0.0} and {@code 1.0} from this random |
|
355 |
* number generator's sequence. |
|
356 |
* |
|
357 |
* <p>The general contract of {@code nextFloat} is that one |
|
358 |
* {@code float} value, chosen (approximately) uniformly from the |
|
359 |
* 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
|
360 |
* 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
|
361 |
* {@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
|
362 |
* where <i>m</i> is a positive integer less than 2<sup>24</sup>, are |
2 | 363 |
* produced with (approximately) equal probability. |
364 |
* |
|
365 |
* <p>The method {@code nextFloat} is implemented by class {@code Random} |
|
366 |
* as if by: |
|
367 |
* <pre> {@code |
|
368 |
* public float nextFloat() { |
|
369 |
* return next(24) / ((float)(1 << 24)); |
|
370 |
* }}</pre> |
|
371 |
* |
|
372 |
* <p>The hedge "approximately" is used in the foregoing description only |
|
373 |
* because the next method is only approximately an unbiased source of |
|
374 |
* independently chosen bits. If it were a perfect source of randomly |
|
375 |
* chosen bits, then the algorithm shown would choose {@code float} |
|
376 |
* values from the stated range with perfect uniformity.<p> |
|
377 |
* [In early versions of Java, the result was incorrectly calculated as: |
|
378 |
* <pre> {@code |
|
379 |
* return next(30) / ((float)(1 << 30));}</pre> |
|
380 |
* This might seem to be equivalent, if not better, but in fact it |
|
381 |
* introduced a slight nonuniformity because of the bias in the rounding |
|
382 |
* of floating-point numbers: it was slightly more likely that the |
|
383 |
* low-order bit of the significand would be 0 than that it would be 1.] |
|
384 |
* |
|
385 |
* @return the next pseudorandom, uniformly distributed {@code float} |
|
386 |
* value between {@code 0.0} and {@code 1.0} from this |
|
387 |
* random number generator's sequence |
|
388 |
*/ |
|
389 |
public float nextFloat() { |
|
390 |
return next(24) / ((float)(1 << 24)); |
|
391 |
} |
|
392 |
||
393 |
/** |
|
394 |
* Returns the next pseudorandom, uniformly distributed |
|
395 |
* {@code double} value between {@code 0.0} and |
|
396 |
* {@code 1.0} from this random number generator's sequence. |
|
397 |
* |
|
398 |
* <p>The general contract of {@code nextDouble} is that one |
|
399 |
* {@code double} value, chosen (approximately) uniformly from the |
|
400 |
* range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is |
|
401 |
* pseudorandomly generated and returned. |
|
402 |
* |
|
403 |
* <p>The method {@code nextDouble} is implemented by class {@code Random} |
|
404 |
* as if by: |
|
405 |
* <pre> {@code |
|
406 |
* public double nextDouble() { |
|
407 |
* return (((long)next(26) << 27) + next(27)) |
|
408 |
* / (double)(1L << 53); |
|
409 |
* }}</pre> |
|
410 |
* |
|
411 |
* <p>The hedge "approximately" is used in the foregoing description only |
|
412 |
* because the {@code next} method is only approximately an unbiased |
|
413 |
* source of independently chosen bits. If it were a perfect source of |
|
414 |
* randomly chosen bits, then the algorithm shown would choose |
|
415 |
* {@code double} values from the stated range with perfect uniformity. |
|
416 |
* <p>[In early versions of Java, the result was incorrectly calculated as: |
|
417 |
* <pre> {@code |
|
418 |
* return (((long)next(27) << 27) + next(27)) |
|
419 |
* / (double)(1L << 54);}</pre> |
|
420 |
* This might seem to be equivalent, if not better, but in fact it |
|
421 |
* introduced a large nonuniformity because of the bias in the rounding |
|
422 |
* of floating-point numbers: it was three times as likely that the |
|
423 |
* low-order bit of the significand would be 0 than that it would be 1! |
|
424 |
* This nonuniformity probably doesn't matter much in practice, but we |
|
425 |
* strive for perfection.] |
|
426 |
* |
|
427 |
* @return the next pseudorandom, uniformly distributed {@code double} |
|
428 |
* value between {@code 0.0} and {@code 1.0} from this |
|
429 |
* random number generator's sequence |
|
430 |
* @see Math#random |
|
431 |
*/ |
|
432 |
public double nextDouble() { |
|
19609
108f52a7438f
8023155: Ensure functional consistency across Random, ThreadLocalRandom, SplittableRandom
psandoz
parents:
19074
diff
changeset
|
433 |
return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT; |
2 | 434 |
} |
435 |
||
436 |
private double nextNextGaussian; |
|
437 |
private boolean haveNextNextGaussian = false; |
|
438 |
||
439 |
/** |
|
440 |
* Returns the next pseudorandom, Gaussian ("normally") distributed |
|
441 |
* {@code double} value with mean {@code 0.0} and standard |
|
442 |
* deviation {@code 1.0} from this random number generator's sequence. |
|
443 |
* <p> |
|
444 |
* The general contract of {@code nextGaussian} is that one |
|
445 |
* {@code double} value, chosen from (approximately) the usual |
|
446 |
* normal distribution with mean {@code 0.0} and standard deviation |
|
447 |
* {@code 1.0}, is pseudorandomly generated and returned. |
|
448 |
* |
|
449 |
* <p>The method {@code nextGaussian} is implemented by class |
|
450 |
* {@code Random} as if by a threadsafe version of the following: |
|
451 |
* <pre> {@code |
|
452 |
* private double nextNextGaussian; |
|
453 |
* private boolean haveNextNextGaussian = false; |
|
454 |
* |
|
455 |
* public double nextGaussian() { |
|
456 |
* if (haveNextNextGaussian) { |
|
457 |
* haveNextNextGaussian = false; |
|
458 |
* return nextNextGaussian; |
|
459 |
* } else { |
|
460 |
* double v1, v2, s; |
|
461 |
* do { |
|
462 |
* v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0 |
|
463 |
* v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0 |
|
464 |
* s = v1 * v1 + v2 * v2; |
|
465 |
* } while (s >= 1 || s == 0); |
|
466 |
* double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s); |
|
467 |
* nextNextGaussian = v2 * multiplier; |
|
468 |
* haveNextNextGaussian = true; |
|
469 |
* return v1 * multiplier; |
|
470 |
* } |
|
471 |
* }}</pre> |
|
472 |
* This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and |
|
473 |
* G. Marsaglia, as described by Donald E. Knuth in <i>The Art of |
|
43003
b1c1a42602d6
8164923: Error in the documentation for java.lang.Random
rriggs
parents:
33674
diff
changeset
|
474 |
* Computer Programming</i>, Volume 2: <i>Seminumerical Algorithms</i>, |
2 | 475 |
* section 3.4.1, subsection C, algorithm P. Note that it generates two |
476 |
* independent values at the cost of only one call to {@code StrictMath.log} |
|
477 |
* and one call to {@code StrictMath.sqrt}. |
|
478 |
* |
|
479 |
* @return the next pseudorandom, Gaussian ("normally") distributed |
|
480 |
* {@code double} value with mean {@code 0.0} and |
|
481 |
* standard deviation {@code 1.0} from this random number |
|
482 |
* generator's sequence |
|
483 |
*/ |
|
32649
2ee9017c7597
8136583: Core libraries should use blessed modifier order
martin
parents:
25859
diff
changeset
|
484 |
public synchronized double nextGaussian() { |
2 | 485 |
// See Knuth, ACP, Section 3.4.1 Algorithm C. |
486 |
if (haveNextNextGaussian) { |
|
487 |
haveNextNextGaussian = false; |
|
488 |
return nextNextGaussian; |
|
489 |
} else { |
|
490 |
double v1, v2, s; |
|
491 |
do { |
|
492 |
v1 = 2 * nextDouble() - 1; // between -1 and 1 |
|
493 |
v2 = 2 * nextDouble() - 1; // between -1 and 1 |
|
494 |
s = v1 * v1 + v2 * v2; |
|
495 |
} while (s >= 1 || s == 0); |
|
496 |
double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s); |
|
497 |
nextNextGaussian = v2 * multiplier; |
|
498 |
haveNextNextGaussian = true; |
|
499 |
return v1 * multiplier; |
|
500 |
} |
|
501 |
} |
|
502 |
||
17421
f3fbcfe6e2cf
8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
mduigou
parents:
14342
diff
changeset
|
503 |
/** |
2 | 504 |
* Serializable fields for Random. |
505 |
* |
|
506 |
* @serialField seed long |
|
507 |
* seed for random computations |
|
508 |
* @serialField nextNextGaussian double |
|
509 |
* next Gaussian to be returned |
|
510 |
* @serialField haveNextNextGaussian boolean |
|
511 |
* nextNextGaussian is valid |
|
512 |
*/ |
|
57956
e0b8b019d2f5
8229997: Apply java.io.Serial annotations in java.base
darcy
parents:
52220
diff
changeset
|
513 |
@java.io.Serial |
2 | 514 |
private static final ObjectStreamField[] serialPersistentFields = { |
515 |
new ObjectStreamField("seed", Long.TYPE), |
|
516 |
new ObjectStreamField("nextNextGaussian", Double.TYPE), |
|
517 |
new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE) |
|
518 |
}; |
|
519 |
||
520 |
/** |
|
521 |
* Reconstitute the {@code Random} instance from a stream (that is, |
|
522 |
* deserialize it). |
|
523 |
*/ |
|
57956
e0b8b019d2f5
8229997: Apply java.io.Serial annotations in java.base
darcy
parents:
52220
diff
changeset
|
524 |
@java.io.Serial |
2 | 525 |
private void readObject(java.io.ObjectInputStream s) |
526 |
throws java.io.IOException, ClassNotFoundException { |
|
527 |
||
528 |
ObjectInputStream.GetField fields = s.readFields(); |
|
529 |
||
530 |
// The seed is read in as {@code long} for |
|
531 |
// historical reasons, but it is converted to an AtomicLong. |
|
51 | 532 |
long seedVal = fields.get("seed", -1L); |
2 | 533 |
if (seedVal < 0) |
534 |
throw new java.io.StreamCorruptedException( |
|
535 |
"Random: invalid seed"); |
|
536 |
resetSeed(seedVal); |
|
537 |
nextNextGaussian = fields.get("nextNextGaussian", 0.0); |
|
538 |
haveNextNextGaussian = fields.get("haveNextNextGaussian", false); |
|
539 |
} |
|
540 |
||
541 |
/** |
|
542 |
* Save the {@code Random} instance to a stream. |
|
543 |
*/ |
|
57956
e0b8b019d2f5
8229997: Apply java.io.Serial annotations in java.base
darcy
parents:
52220
diff
changeset
|
544 |
@java.io.Serial |
32649
2ee9017c7597
8136583: Core libraries should use blessed modifier order
martin
parents:
25859
diff
changeset
|
545 |
private synchronized void writeObject(ObjectOutputStream s) |
2 | 546 |
throws IOException { |
547 |
||
548 |
// set the values of the Serializable fields |
|
549 |
ObjectOutputStream.PutField fields = s.putFields(); |
|
550 |
||
551 |
// The seed is serialized as a long for historical reasons. |
|
552 |
fields.put("seed", seed.get()); |
|
553 |
fields.put("nextNextGaussian", nextNextGaussian); |
|
554 |
fields.put("haveNextNextGaussian", haveNextNextGaussian); |
|
555 |
||
556 |
// save them |
|
557 |
s.writeFields(); |
|
558 |
} |
|
559 |
||
560 |
// Support for resetting seed while deserializing |
|
561 |
private static final Unsafe unsafe = Unsafe.getUnsafe(); |
|
562 |
private static final long seedOffset; |
|
563 |
static { |
|
564 |
try { |
|
565 |
seedOffset = unsafe.objectFieldOffset |
|
566 |
(Random.class.getDeclaredField("seed")); |
|
567 |
} catch (Exception ex) { throw new Error(ex); } |
|
568 |
} |
|
569 |
private void resetSeed(long seedVal) { |
|
52220
9c260a6b6471
8207146: Rename jdk.internal.misc.Unsafe::xxxObject to xxxReference
mchung
parents:
51759
diff
changeset
|
570 |
unsafe.putReferenceVolatile(this, seedOffset, new AtomicLong(seedVal)); |
2 | 571 |
} |
59086 | 572 |
|
573 |
// Methods required by class AbstractSpliteratorGenerator |
|
574 |
public Spliterator.OfInt makeIntsSpliterator(long index, long fence, int origin, int bound) { |
|
575 |
return new RandomIntsSpliterator(this, index, fence, origin, bound); |
|
576 |
} |
|
577 |
public Spliterator.OfLong makeLongsSpliterator(long index, long fence, long origin, long bound) { |
|
578 |
return new RandomLongsSpliterator(this, index, fence, origin, bound); |
|
579 |
} |
|
580 |
public Spliterator.OfDouble makeDoublesSpliterator(long index, long fence, double origin, double bound) { |
|
581 |
return new RandomDoublesSpliterator(this, index, fence, origin, bound); |
|
582 |
} |
|
583 |
||
584 |
/** |
|
585 |
* Spliterators for producing streams. These are based on abstract spliterator classes provided |
|
586 |
* by class AbstractSpliteratorGenerator. Each one needs to define only a constructor and two |
|
587 |
* methods. |
|
588 |
*/ |
|
589 |
static class RandomIntsSpliterator extends RandomSupport.RandomSpliterator |
|
590 |
implements Spliterator.OfInt { |
|
591 |
final AbstractSpliteratorGenerator generatingGenerator; |
|
592 |
final int origin; |
|
593 |
final int bound; |
|
594 |
||
595 |
RandomIntsSpliterator(AbstractSpliteratorGenerator generatingGenerator, |
|
596 |
long index, long fence, int origin, int bound) { |
|
597 |
super(index, fence); |
|
598 |
this.generatingGenerator = generatingGenerator; |
|
599 |
this.origin = origin; this.bound = bound; |
|
600 |
} |
|
601 |
||
602 |
public Spliterator.OfInt trySplit() { |
|
603 |
long i = index, m = (i + fence) >>> 1; |
|
604 |
if (m <= i) return null; |
|
605 |
index = m; |
|
606 |
// The same generatingGenerator is used, with no splitting or copying. |
|
607 |
return new RandomIntsSpliterator(generatingGenerator, i, m, origin, bound); |
|
608 |
} |
|
609 |
||
610 |
public boolean tryAdvance(IntConsumer consumer) { |
|
611 |
if (consumer == null) throw new NullPointerException(); |
|
612 |
long i = index, f = fence; |
|
613 |
if (i < f) { |
|
614 |
consumer.accept(RandomSupport.boundedNextInt(generatingGenerator, origin, bound)); |
|
615 |
index = i + 1; |
|
616 |
return true; |
|
617 |
} |
|
618 |
else return false; |
|
619 |
} |
|
620 |
||
621 |
public void forEachRemaining(IntConsumer consumer) { |
|
622 |
if (consumer == null) throw new NullPointerException(); |
|
623 |
long i = index, f = fence; |
|
624 |
if (i < f) { |
|
625 |
index = f; |
|
626 |
RandomGenerator r = generatingGenerator; |
|
627 |
int o = origin, b = bound; |
|
628 |
do { |
|
629 |
consumer.accept(RandomSupport.boundedNextInt(r, o, b)); |
|
630 |
} while (++i < f); |
|
631 |
} |
|
632 |
} |
|
633 |
} |
|
634 |
||
635 |
/** |
|
636 |
* Spliterator for long streams. |
|
637 |
*/ |
|
638 |
static class RandomLongsSpliterator extends RandomSupport.RandomSpliterator |
|
639 |
implements Spliterator.OfLong { |
|
640 |
final AbstractSpliteratorGenerator generatingGenerator; |
|
641 |
final long origin; |
|
642 |
final long bound; |
|
643 |
||
644 |
RandomLongsSpliterator(AbstractSpliteratorGenerator generatingGenerator, |
|
645 |
long index, long fence, long origin, long bound) { |
|
646 |
super(index, fence); |
|
647 |
this.generatingGenerator = generatingGenerator; |
|
648 |
this.origin = origin; this.bound = bound; |
|
649 |
} |
|
650 |
||
651 |
public Spliterator.OfLong trySplit() { |
|
652 |
long i = index, m = (i + fence) >>> 1; |
|
653 |
if (m <= i) return null; |
|
654 |
index = m; |
|
655 |
// The same generatingGenerator is used, with no splitting or copying. |
|
656 |
return new RandomLongsSpliterator(generatingGenerator, i, m, origin, bound); |
|
657 |
} |
|
658 |
||
659 |
public boolean tryAdvance(LongConsumer consumer) { |
|
660 |
if (consumer == null) throw new NullPointerException(); |
|
661 |
long i = index, f = fence; |
|
662 |
if (i < f) { |
|
663 |
consumer.accept(RandomSupport.boundedNextLong(generatingGenerator, origin, bound)); |
|
664 |
index = i + 1; |
|
665 |
return true; |
|
666 |
} |
|
667 |
else return false; |
|
668 |
} |
|
669 |
||
670 |
public void forEachRemaining(LongConsumer consumer) { |
|
671 |
if (consumer == null) throw new NullPointerException(); |
|
672 |
long i = index, f = fence; |
|
673 |
if (i < f) { |
|
674 |
index = f; |
|
675 |
RandomGenerator r = generatingGenerator; |
|
676 |
long o = origin, b = bound; |
|
677 |
do { |
|
678 |
consumer.accept(RandomSupport.boundedNextLong(r, o, b)); |
|
679 |
} while (++i < f); |
|
680 |
} |
|
681 |
} |
|
682 |
} |
|
683 |
||
684 |
/** |
|
685 |
* Spliterator for double streams. |
|
686 |
*/ |
|
687 |
static class RandomDoublesSpliterator extends RandomSupport.RandomSpliterator |
|
688 |
implements Spliterator.OfDouble { |
|
689 |
final AbstractSpliteratorGenerator generatingGenerator; |
|
690 |
final double origin; |
|
691 |
final double bound; |
|
692 |
||
693 |
RandomDoublesSpliterator(AbstractSpliteratorGenerator generatingGenerator, |
|
694 |
long index, long fence, double origin, double bound) { |
|
695 |
super(index, fence); |
|
696 |
this.generatingGenerator = generatingGenerator; |
|
697 |
this.origin = origin; this.bound = bound; |
|
698 |
} |
|
699 |
||
700 |
public Spliterator.OfDouble trySplit() { |
|
701 |
long i = index, m = (i + fence) >>> 1; |
|
702 |
if (m <= i) return null; |
|
703 |
index = m; |
|
704 |
// The same generatingGenerator is used, with no splitting or copying. |
|
705 |
return new RandomDoublesSpliterator(generatingGenerator, i, m, origin, bound); |
|
706 |
} |
|
707 |
||
708 |
public boolean tryAdvance(DoubleConsumer consumer) { |
|
709 |
if (consumer == null) throw new NullPointerException(); |
|
710 |
long i = index, f = fence; |
|
711 |
if (i < f) { |
|
712 |
consumer.accept(RandomSupport.boundedNextDouble(generatingGenerator, origin, bound)); |
|
713 |
index = i + 1; |
|
714 |
return true; |
|
715 |
} |
|
716 |
else return false; |
|
717 |
} |
|
718 |
||
719 |
public void forEachRemaining(DoubleConsumer consumer) { |
|
720 |
if (consumer == null) throw new NullPointerException(); |
|
721 |
long i = index, f = fence; |
|
722 |
if (i < f) { |
|
723 |
index = f; |
|
724 |
RandomGenerator r = generatingGenerator; |
|
725 |
double o = origin, b = bound; |
|
726 |
do { |
|
727 |
consumer.accept(RandomSupport.boundedNextDouble(r, o, b)); |
|
728 |
} while (++i < f); |
|
729 |
} |
|
730 |
} |
|
731 |
} |
|
2 | 732 |
} |