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