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