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