1. /*
  2. * @(#)Random.java 1.43 04/01/12
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util;
  8. import java.io.*;
  9. import java.util.concurrent.atomic.AtomicLong;
  10. /**
  11. * An instance of this class is used to generate a stream of
  12. * pseudorandom numbers. The class uses a 48-bit seed, which is
  13. * modified using a linear congruential formula. (See Donald Knuth,
  14. * <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
  15. * <p>
  16. * If two instances of <code>Random</code> are created with the same
  17. * seed, and the same sequence of method calls is made for each, they
  18. * will generate and return identical sequences of numbers. In order to
  19. * guarantee this property, particular algorithms are specified for the
  20. * class <tt>Random</tt>. Java implementations must use all the algorithms
  21. * shown here for the class <tt>Random</tt>, for the sake of absolute
  22. * portability of Java code. However, subclasses of class <tt>Random</tt>
  23. * are permitted to use other algorithms, so long as they adhere to the
  24. * general contracts for all the methods.
  25. * <p>
  26. * The algorithms implemented by class <tt>Random</tt> use a
  27. * <tt>protected</tt> utility method that on each invocation can supply
  28. * up to 32 pseudorandomly generated bits.
  29. * <p>
  30. * Many applications will find the <code>random</code> method in
  31. * class <code>Math</code> simpler to use.
  32. *
  33. * @author Frank Yellin
  34. * @version 1.43, 01/12/04
  35. * @see java.lang.Math#random()
  36. * @since JDK1.0
  37. */
  38. public
  39. class Random implements java.io.Serializable {
  40. /** use serialVersionUID from JDK 1.1 for interoperability */
  41. static final long serialVersionUID = 3905348978240129619L;
  42. /**
  43. * The internal state associated with this pseudorandom number generator.
  44. * (The specs for the methods in this class describe the ongoing
  45. * computation of this value.)
  46. *
  47. * @serial
  48. */
  49. private AtomicLong seed;
  50. private final static long multiplier = 0x5DEECE66DL;
  51. private final static long addend = 0xBL;
  52. private final static long mask = (1L << 48) - 1;
  53. /**
  54. * Creates a new random number generator. This constructor sets
  55. * the seed of the random number generator to a value very likely
  56. * to be distinct from any other invocation of this constructor.
  57. */
  58. public Random() { this(++seedUniquifier + System.nanoTime()); }
  59. private static volatile long seedUniquifier = 8682522807148012L;
  60. /**
  61. * Creates a new random number generator using a single
  62. * <code>long</code> seed:
  63. * <blockquote><pre>
  64. * public Random(long seed) { setSeed(seed); }</pre></blockquote>
  65. * Used by method <tt>next</tt> to hold
  66. * the state of the pseudorandom number generator.
  67. *
  68. * @param seed the initial seed.
  69. * @see java.util.Random#setSeed(long)
  70. */
  71. public Random(long seed) {
  72. this.seed = new AtomicLong(0L);
  73. setSeed(seed);
  74. }
  75. /**
  76. * Sets the seed of this random number generator using a single
  77. * <code>long</code> seed. The general contract of <tt>setSeed</tt>
  78. * is that it alters the state of this random number generator
  79. * object so as to be in exactly the same state as if it had just
  80. * been created with the argument <tt>seed</tt> as a seed. The method
  81. * <tt>setSeed</tt> is implemented by class Random as follows:
  82. * <blockquote><pre>
  83. * synchronized public void setSeed(long seed) {
  84. * this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);
  85. * haveNextNextGaussian = false;
  86. * }</pre></blockquote>
  87. * The implementation of <tt>setSeed</tt> by class <tt>Random</tt>
  88. * happens to use only 48 bits of the given seed. In general, however,
  89. * an overriding method may use all 64 bits of the long argument
  90. * as a seed value.
  91. *
  92. * Note: Although the seed value is an AtomicLong, this method
  93. * must still be synchronized to ensure correct semantics
  94. * of haveNextNextGaussian.
  95. *
  96. * @param seed the initial seed.
  97. */
  98. synchronized public void setSeed(long seed) {
  99. seed = (seed ^ multiplier) & mask;
  100. this.seed.set(seed);
  101. haveNextNextGaussian = false;
  102. }
  103. /**
  104. * Generates the next pseudorandom number. Subclass should
  105. * override this, as this is used by all other methods.<p>
  106. * The general contract of <tt>next</tt> is that it returns an
  107. * <tt>int</tt> value and if the argument bits is between <tt>1</tt>
  108. * and <tt>32</tt> (inclusive), then that many low-order bits of the
  109. * returned value will be (approximately) independently chosen bit
  110. * values, each of which is (approximately) equally likely to be
  111. * <tt>0</tt> or <tt>1</tt>. The method <tt>next</tt> is implemented
  112. * by class <tt>Random</tt> as follows:
  113. * <blockquote><pre>
  114. * synchronized protected int next(int bits) {
  115. * seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
  116. * return (int)(seed >>> (48 - bits));
  117. * }</pre></blockquote>
  118. * This is a linear congruential pseudorandom number generator, as
  119. * defined by D. H. Lehmer and described by Donald E. Knuth in <i>The
  120. * Art of Computer Programming,</i> Volume 2: <i>Seminumerical
  121. * Algorithms</i>, section 3.2.1.
  122. *
  123. * @param bits random bits
  124. * @return the next pseudorandom value from this random number generator's sequence.
  125. * @since JDK1.1
  126. */
  127. protected int next(int bits) {
  128. long oldseed, nextseed;
  129. AtomicLong seed = this.seed;
  130. do {
  131. oldseed = seed.get();
  132. nextseed = (oldseed * multiplier + addend) & mask;
  133. } while (!seed.compareAndSet(oldseed, nextseed));
  134. return (int)(nextseed >>> (48 - bits));
  135. }
  136. private static final int BITS_PER_BYTE = 8;
  137. private static final int BYTES_PER_INT = 4;
  138. /**
  139. * Generates random bytes and places them into a user-supplied
  140. * byte array. The number of random bytes produced is equal to
  141. * the length of the byte array.
  142. *
  143. * @param bytes the non-null byte array in which to put the
  144. * random bytes.
  145. * @since JDK1.1
  146. */
  147. public void nextBytes(byte[] bytes) {
  148. int numRequested = bytes.length;
  149. int numGot = 0, rnd = 0;
  150. while (true) {
  151. for (int i = 0; i < BYTES_PER_INT; i++) {
  152. if (numGot == numRequested)
  153. return;
  154. rnd = (i==0 ? next(BITS_PER_BYTE * BYTES_PER_INT)
  155. : rnd >> BITS_PER_BYTE);
  156. bytes[numGot++] = (byte)rnd;
  157. }
  158. }
  159. }
  160. /**
  161. * Returns the next pseudorandom, uniformly distributed <code>int</code>
  162. * value from this random number generator's sequence. The general
  163. * contract of <tt>nextInt</tt> is that one <tt>int</tt> value is
  164. * pseudorandomly generated and returned. All 2<font size="-1"><sup>32
  165. * </sup></font> possible <tt>int</tt> values are produced with
  166. * (approximately) equal probability. The method <tt>nextInt</tt> is
  167. * implemented by class <tt>Random</tt> as follows:
  168. * <blockquote><pre>
  169. * public int nextInt() { return next(32); }</pre></blockquote>
  170. *
  171. * @return the next pseudorandom, uniformly distributed <code>int</code>
  172. * value from this random number generator's sequence.
  173. */
  174. public int nextInt() { return next(32); }
  175. /**
  176. * Returns a pseudorandom, uniformly distributed <tt>int</tt> value
  177. * between 0 (inclusive) and the specified value (exclusive), drawn from
  178. * this random number generator's sequence. The general contract of
  179. * <tt>nextInt</tt> is that one <tt>int</tt> value in the specified range
  180. * is pseudorandomly generated and returned. All <tt>n</tt> possible
  181. * <tt>int</tt> values are produced with (approximately) equal
  182. * probability. The method <tt>nextInt(int n)</tt> is implemented by
  183. * class <tt>Random</tt> as follows:
  184. * <blockquote><pre>
  185. * public int nextInt(int n) {
  186. * if (n<=0)
  187. * throw new IllegalArgumentException("n must be positive");
  188. *
  189. * if ((n & -n) == n) // i.e., n is a power of 2
  190. * return (int)((n * (long)next(31)) >> 31);
  191. *
  192. * int bits, val;
  193. * do {
  194. * bits = next(31);
  195. * val = bits % n;
  196. * } while(bits - val + (n-1) < 0);
  197. * return val;
  198. * }
  199. * </pre></blockquote>
  200. * <p>
  201. * The hedge "approximately" is used in the foregoing description only
  202. * because the next method is only approximately an unbiased source of
  203. * independently chosen bits. If it were a perfect source of randomly
  204. * chosen bits, then the algorithm shown would choose <tt>int</tt>
  205. * values from the stated range with perfect uniformity.
  206. * <p>
  207. * The algorithm is slightly tricky. It rejects values that would result
  208. * in an uneven distribution (due to the fact that 2^31 is not divisible
  209. * by n). The probability of a value being rejected depends on n. The
  210. * worst case is n=2^30+1, for which the probability of a reject is 1/2,
  211. * and the expected number of iterations before the loop terminates is 2.
  212. * <p>
  213. * The algorithm treats the case where n is a power of two specially: it
  214. * returns the correct number of high-order bits from the underlying
  215. * pseudo-random number generator. In the absence of special treatment,
  216. * the correct number of <i>low-order</i> bits would be returned. Linear
  217. * congruential pseudo-random number generators such as the one
  218. * implemented by this class are known to have short periods in the
  219. * sequence of values of their low-order bits. Thus, this special case
  220. * greatly increases the length of the sequence of values returned by
  221. * successive calls to this method if n is a small power of two.
  222. *
  223. * @param n the bound on the random number to be returned. Must be
  224. * positive.
  225. * @return a pseudorandom, uniformly distributed <tt>int</tt>
  226. * value between 0 (inclusive) and n (exclusive).
  227. * @exception IllegalArgumentException n is not positive.
  228. * @since 1.2
  229. */
  230. public int nextInt(int n) {
  231. if (n<=0)
  232. throw new IllegalArgumentException("n must be positive");
  233. if ((n & -n) == n) // i.e., n is a power of 2
  234. return (int)((n * (long)next(31)) >> 31);
  235. int bits, val;
  236. do {
  237. bits = next(31);
  238. val = bits % n;
  239. } while(bits - val + (n-1) < 0);
  240. return val;
  241. }
  242. /**
  243. * Returns the next pseudorandom, uniformly distributed <code>long</code>
  244. * value from this random number generator's sequence. The general
  245. * contract of <tt>nextLong</tt> is that one long value is pseudorandomly
  246. * generated and returned. All 2<font size="-1"><sup>64</sup></font>
  247. * possible <tt>long</tt> values are produced with (approximately) equal
  248. * probability. The method <tt>nextLong</tt> is implemented by class
  249. * <tt>Random</tt> as follows:
  250. * <blockquote><pre>
  251. * public long nextLong() {
  252. * return ((long)next(32) << 32) + next(32);
  253. * }</pre></blockquote>
  254. *
  255. * @return the next pseudorandom, uniformly distributed <code>long</code>
  256. * value from this random number generator's sequence.
  257. */
  258. public long nextLong() {
  259. // it's okay that the bottom word remains signed.
  260. return ((long)(next(32)) << 32) + next(32);
  261. }
  262. /**
  263. * Returns the next pseudorandom, uniformly distributed
  264. * <code>boolean</code> value from this random number generator's
  265. * sequence. The general contract of <tt>nextBoolean</tt> is that one
  266. * <tt>boolean</tt> value is pseudorandomly generated and returned. The
  267. * values <code>true</code> and <code>false</code> are produced with
  268. * (approximately) equal probability. The method <tt>nextBoolean</tt> is
  269. * implemented by class <tt>Random</tt> as follows:
  270. * <blockquote><pre>
  271. * public boolean nextBoolean() {return next(1) != 0;}
  272. * </pre></blockquote>
  273. * @return the next pseudorandom, uniformly distributed
  274. * <code>boolean</code> value from this random number generator's
  275. * sequence.
  276. * @since 1.2
  277. */
  278. public boolean nextBoolean() {return next(1) != 0;}
  279. /**
  280. * Returns the next pseudorandom, uniformly distributed <code>float</code>
  281. * value between <code>0.0</code> and <code>1.0</code> from this random
  282. * number generator's sequence. <p>
  283. * The general contract of <tt>nextFloat</tt> is that one <tt>float</tt>
  284. * value, chosen (approximately) uniformly from the range <tt>0.0f</tt>
  285. * (inclusive) to <tt>1.0f</tt> (exclusive), is pseudorandomly
  286. * generated and returned. All 2<font size="-1"><sup>24</sup></font>
  287. * possible <tt>float</tt> values of the form
  288. * <i>m x </i>2<font size="-1"><sup>-24</sup></font>, where
  289. * <i>m</i> is a positive integer less than 2<font size="-1"><sup>24</sup>
  290. * </font>, are produced with (approximately) equal probability. The
  291. * method <tt>nextFloat</tt> is implemented by class <tt>Random</tt> as
  292. * follows:
  293. * <blockquote><pre>
  294. * public float nextFloat() {
  295. * return next(24) / ((float)(1 << 24));
  296. * }</pre></blockquote>
  297. * The hedge "approximately" is used in the foregoing description only
  298. * because the next method is only approximately an unbiased source of
  299. * independently chosen bits. If it were a perfect source or randomly
  300. * chosen bits, then the algorithm shown would choose <tt>float</tt>
  301. * values from the stated range with perfect uniformity.<p>
  302. * [In early versions of Java, the result was incorrectly calculated as:
  303. * <blockquote><pre>
  304. * return next(30) / ((float)(1 << 30));</pre></blockquote>
  305. * This might seem to be equivalent, if not better, but in fact it
  306. * introduced a slight nonuniformity because of the bias in the rounding
  307. * of floating-point numbers: it was slightly more likely that the
  308. * low-order bit of the significand would be 0 than that it would be 1.]
  309. *
  310. * @return the next pseudorandom, uniformly distributed <code>float</code>
  311. * value between <code>0.0</code> and <code>1.0</code> from this
  312. * random number generator's sequence.
  313. */
  314. public float nextFloat() {
  315. int i = next(24);
  316. return i / ((float)(1 << 24));
  317. }
  318. /**
  319. * Returns the next pseudorandom, uniformly distributed
  320. * <code>double</code> value between <code>0.0</code> and
  321. * <code>1.0</code> from this random number generator's sequence. <p>
  322. * The general contract of <tt>nextDouble</tt> is that one
  323. * <tt>double</tt> value, chosen (approximately) uniformly from the
  324. * range <tt>0.0d</tt> (inclusive) to <tt>1.0d</tt> (exclusive), is
  325. * pseudorandomly generated and returned. All
  326. * 2<font size="-1"><sup>53</sup></font> possible <tt>float</tt>
  327. * values of the form <i>m x </i>2<font size="-1"><sup>-53</sup>
  328. * </font>, where <i>m</i> is a positive integer less than
  329. * 2<font size="-1"><sup>53</sup></font>, are produced with
  330. * (approximately) equal probability. The method <tt>nextDouble</tt> is
  331. * implemented by class <tt>Random</tt> as follows:
  332. * <blockquote><pre>
  333. * public double nextDouble() {
  334. * return (((long)next(26) << 27) + next(27))
  335. * / (double)(1L << 53);
  336. * }</pre></blockquote><p>
  337. * The hedge "approximately" is used in the foregoing description only
  338. * because the <tt>next</tt> method is only approximately an unbiased
  339. * source of independently chosen bits. If it were a perfect source or
  340. * randomly chosen bits, then the algorithm shown would choose
  341. * <tt>double</tt> values from the stated range with perfect uniformity.
  342. * <p>[In early versions of Java, the result was incorrectly calculated as:
  343. * <blockquote><pre>
  344. * return (((long)next(27) << 27) + next(27))
  345. * / (double)(1L << 54);</pre></blockquote>
  346. * This might seem to be equivalent, if not better, but in fact it
  347. * introduced a large nonuniformity because of the bias in the rounding
  348. * of floating-point numbers: it was three times as likely that the
  349. * low-order bit of the significand would be 0 than that it would be
  350. * 1! This nonuniformity probably doesn't matter much in practice, but
  351. * we strive for perfection.]
  352. *
  353. * @return the next pseudorandom, uniformly distributed
  354. * <code>double</code> value between <code>0.0</code> and
  355. * <code>1.0</code> from this random number generator's sequence.
  356. */
  357. public double nextDouble() {
  358. long l = ((long)(next(26)) << 27) + next(27);
  359. return l / (double)(1L << 53);
  360. }
  361. private double nextNextGaussian;
  362. private boolean haveNextNextGaussian = false;
  363. /**
  364. * Returns the next pseudorandom, Gaussian ("normally") distributed
  365. * <code>double</code> value with mean <code>0.0</code> and standard
  366. * deviation <code>1.0</code> from this random number generator's sequence.
  367. * <p>
  368. * The general contract of <tt>nextGaussian</tt> is that one
  369. * <tt>double</tt> value, chosen from (approximately) the usual
  370. * normal distribution with mean <tt>0.0</tt> and standard deviation
  371. * <tt>1.0</tt>, is pseudorandomly generated and returned. The method
  372. * <tt>nextGaussian</tt> is implemented by class <tt>Random</tt> as follows:
  373. * <blockquote><pre>
  374. * synchronized public double nextGaussian() {
  375. * if (haveNextNextGaussian) {
  376. * haveNextNextGaussian = false;
  377. * return nextNextGaussian;
  378. * } else {
  379. * double v1, v2, s;
  380. * do {
  381. * v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
  382. * v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0
  383. * s = v1 * v1 + v2 * v2;
  384. * } while (s >= 1 || s == 0);
  385. * double multiplier = Math.sqrt(-2 * Math.log(s)/s);
  386. * nextNextGaussian = v2 * multiplier;
  387. * haveNextNextGaussian = true;
  388. * return v1 * multiplier;
  389. * }
  390. * }</pre></blockquote>
  391. * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
  392. * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
  393. * Computer Programming</i>, Volume 2: <i>Seminumerical Algorithms</i>,
  394. * section 3.4.1, subsection C, algorithm P. Note that it generates two
  395. * independent values at the cost of only one call to <tt>Math.log</tt>
  396. * and one call to <tt>Math.sqrt</tt>.
  397. *
  398. * @return the next pseudorandom, Gaussian ("normally") distributed
  399. * <code>double</code> value with mean <code>0.0</code> and
  400. * standard deviation <code>1.0</code> from this random number
  401. * generator's sequence.
  402. */
  403. synchronized public double nextGaussian() {
  404. // See Knuth, ACP, Section 3.4.1 Algorithm C.
  405. if (haveNextNextGaussian) {
  406. haveNextNextGaussian = false;
  407. return nextNextGaussian;
  408. } else {
  409. double v1, v2, s;
  410. do {
  411. v1 = 2 * nextDouble() - 1; // between -1 and 1
  412. v2 = 2 * nextDouble() - 1; // between -1 and 1
  413. s = v1 * v1 + v2 * v2;
  414. } while (s >= 1 || s == 0);
  415. double multiplier = Math.sqrt(-2 * Math.log(s)/s);
  416. nextNextGaussian = v2 * multiplier;
  417. haveNextNextGaussian = true;
  418. return v1 * multiplier;
  419. }
  420. }
  421. /**
  422. * Serializable fields for Random.
  423. *
  424. * @serialField seed long;
  425. * seed for random computations
  426. * @serialField nextNextGaussian double;
  427. * next Gaussian to be returned
  428. * @serialField haveNextNextGaussian boolean
  429. * nextNextGaussian is valid
  430. */
  431. private static final ObjectStreamField[] serialPersistentFields = {
  432. new ObjectStreamField("seed", Long.TYPE),
  433. new ObjectStreamField("nextNextGaussian", Double.TYPE),
  434. new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE)
  435. };
  436. /**
  437. * Reconstitute the <tt>Random</tt> instance from a stream (that is,
  438. * deserialize it). The seed is read in as long for
  439. * historical reasons, but it is converted to an AtomicLong.
  440. */
  441. private void readObject(java.io.ObjectInputStream s)
  442. throws java.io.IOException, ClassNotFoundException {
  443. ObjectInputStream.GetField fields = s.readFields();
  444. long seedVal;
  445. seedVal = (long) fields.get("seed", -1L);
  446. if (seedVal < 0)
  447. throw new java.io.StreamCorruptedException(
  448. "Random: invalid seed");
  449. seed = new AtomicLong(seedVal);
  450. nextNextGaussian = fields.get("nextNextGaussian", 0.0);
  451. haveNextNextGaussian = fields.get("haveNextNextGaussian", false);
  452. }
  453. /**
  454. * Save the <tt>Random</tt> instance to a stream.
  455. * The seed of a Random is serialized as a long for
  456. * historical reasons.
  457. *
  458. */
  459. synchronized private void writeObject(ObjectOutputStream s) throws IOException {
  460. // set the values of the Serializable fields
  461. ObjectOutputStream.PutField fields = s.putFields();
  462. fields.put("seed", seed.get());
  463. fields.put("nextNextGaussian", nextNextGaussian);
  464. fields.put("haveNextNextGaussian", haveNextNextGaussian);
  465. // save them
  466. s.writeFields();
  467. }
  468. }