Random.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. /* Random.java -- a pseudo-random number generator
  2. Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util;
  32. import java.io.Serializable;
  33. /**
  34. * This class generates pseudorandom numbers. It uses the same
  35. * algorithm as the original JDK-class, so that your programs behave
  36. * exactly the same way, if started with the same seed.
  37. *
  38. * The algorithm is described in <em>The Art of Computer Programming,
  39. * Volume 2</em> by Donald Knuth in Section 3.2.1. It is a 48-bit seed,
  40. * linear congruential formula.
  41. *
  42. * If two instances of this class are created with the same seed and
  43. * the same calls to these classes are made, they behave exactly the
  44. * same way. This should be even true for foreign implementations
  45. * (like this), so every port must use the same algorithm as described
  46. * here.
  47. *
  48. * If you want to implement your own pseudorandom algorithm, you
  49. * should extend this class and overload the <code>next()</code> and
  50. * <code>setSeed(long)</code> method. In that case the above
  51. * paragraph doesn't apply to you.
  52. *
  53. * This class shouldn't be used for security sensitive purposes (like
  54. * generating passwords or encryption keys. See <code>SecureRandom</code>
  55. * in package <code>java.security</code> for this purpose.
  56. *
  57. * For simple random doubles between 0.0 and 1.0, you may consider using
  58. * Math.random instead.
  59. *
  60. * @see java.security.SecureRandom
  61. * @see Math#random()
  62. * @author Jochen Hoenicke
  63. * @author Eric Blake (ebb9@email.byu.edu)
  64. * @status updated to 1.4
  65. */
  66. public class Random implements Serializable
  67. {
  68. /**
  69. * True if the next nextGaussian is available. This is used by
  70. * nextGaussian, which generates two gaussian numbers by one call,
  71. * and returns the second on the second call.
  72. *
  73. * @serial whether nextNextGaussian is available
  74. * @see #nextGaussian()
  75. * @see #nextNextGaussian
  76. */
  77. private boolean haveNextNextGaussian;
  78. /**
  79. * The next nextGaussian, when available. This is used by nextGaussian,
  80. * which generates two gaussian numbers by one call, and returns the
  81. * second on the second call.
  82. *
  83. * @serial the second gaussian of a pair
  84. * @see #nextGaussian()
  85. * @see #haveNextNextGaussian
  86. */
  87. private double nextNextGaussian;
  88. /**
  89. * The seed. This is the number set by setSeed and which is used
  90. * in next.
  91. *
  92. * @serial the internal state of this generator
  93. * @see #next(int)
  94. */
  95. private long seed;
  96. /**
  97. * Compatible with JDK 1.0+.
  98. */
  99. private static final long serialVersionUID = 3905348978240129619L;
  100. /**
  101. * Creates a new pseudorandom number generator. The seed is initialized
  102. * to the current time, as if by
  103. * <code>setSeed(System.currentTimeMillis());</code>.
  104. *
  105. * @see System#currentTimeMillis()
  106. */
  107. public Random()
  108. {
  109. this(System.currentTimeMillis());
  110. }
  111. /**
  112. * Creates a new pseudorandom number generator, starting with the
  113. * specified seed, using <code>setSeed(seed);</code>.
  114. *
  115. * @param seed the initial seed
  116. */
  117. public Random(long seed)
  118. {
  119. setSeed(seed);
  120. }
  121. /**
  122. * Sets the seed for this pseudorandom number generator. As described
  123. * above, two instances of the same random class, starting with the
  124. * same seed, should produce the same results, if the same methods
  125. * are called. The implementation for java.util.Random is:
  126. *
  127. <pre>public synchronized void setSeed(long seed)
  128. {
  129. this.seed = (seed ^ 0x5DEECE66DL) & ((1L &lt;&lt; 48) - 1);
  130. haveNextNextGaussian = false;
  131. }</pre>
  132. *
  133. * @param seed the new seed
  134. */
  135. public synchronized void setSeed(long seed)
  136. {
  137. this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);
  138. haveNextNextGaussian = false;
  139. }
  140. /**
  141. * Generates the next pseudorandom number. This returns
  142. * an int value whose <code>bits</code> low order bits are
  143. * independent chosen random bits (0 and 1 are equally likely).
  144. * The implementation for java.util.Random is:
  145. *
  146. <pre>protected synchronized int next(int bits)
  147. {
  148. seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L &lt;&lt; 48) - 1);
  149. return (int) (seed &gt;&gt;&gt; (48 - bits));
  150. }</pre>
  151. *
  152. * @param bits the number of random bits to generate, in the range 1..32
  153. * @return the next pseudorandom value
  154. * @since 1.1
  155. */
  156. protected synchronized int next(int bits)
  157. {
  158. seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
  159. return (int) (seed >>> (48 - bits));
  160. }
  161. /**
  162. * Fills an array of bytes with random numbers. All possible values
  163. * are (approximately) equally likely.
  164. * The JDK documentation gives no implementation, but it seems to be:
  165. *
  166. <pre>public void nextBytes(byte[] bytes)
  167. {
  168. for (int i = 0; i &lt; bytes.length; i += 4)
  169. {
  170. int random = next(32);
  171. for (int j = 0; i + j &lt; bytes.length && j &lt; 4; j++)
  172. {
  173. bytes[i+j] = (byte) (random & 0xff)
  174. random &gt;&gt;= 8;
  175. }
  176. }
  177. }</pre>
  178. *
  179. * @param bytes the byte array that should be filled
  180. * @throws NullPointerException if bytes is null
  181. * @since 1.1
  182. */
  183. public void nextBytes(byte[] bytes)
  184. {
  185. int random;
  186. // Do a little bit unrolling of the above algorithm.
  187. int max = bytes.length & ~0x3;
  188. for (int i = 0; i < max; i += 4)
  189. {
  190. random = next(32);
  191. bytes[i] = (byte) random;
  192. bytes[i + 1] = (byte) (random >> 8);
  193. bytes[i + 2] = (byte) (random >> 16);
  194. bytes[i + 3] = (byte) (random >> 24);
  195. }
  196. if (max < bytes.length)
  197. {
  198. random = next(32);
  199. for (int j = max; j < bytes.length; j++)
  200. {
  201. bytes[j] = (byte) random;
  202. random >>= 8;
  203. }
  204. }
  205. }
  206. /**
  207. * Generates the next pseudorandom number. This returns
  208. * an int value whose 32 bits are independent chosen random bits
  209. * (0 and 1 are equally likely). The implementation for
  210. * java.util.Random is:
  211. *
  212. <pre>public int nextInt()
  213. {
  214. return next(32);
  215. }</pre>
  216. *
  217. * @return the next pseudorandom value
  218. */
  219. public int nextInt()
  220. {
  221. return next(32);
  222. }
  223. /**
  224. * Generates the next pseudorandom number. This returns
  225. * a value between 0(inclusive) and <code>n</code>(exclusive), and
  226. * each value has the same likelihodd (1/<code>n</code>).
  227. * (0 and 1 are equally likely). The implementation for
  228. * java.util.Random is:
  229. *
  230. <pre>
  231. public int nextInt(int n)
  232. {
  233. if (n &lt;= 0)
  234. throw new IllegalArgumentException("n must be positive");
  235. if ((n & -n) == n) // i.e., n is a power of 2
  236. return (int)((n * (long) next(31)) &gt;&gt; 31);
  237. int bits, val;
  238. do
  239. {
  240. bits = next(31);
  241. val = bits % n;
  242. }
  243. while(bits - val + (n-1) &lt; 0);
  244. return val;
  245. }</pre>
  246. *
  247. * <p>This algorithm would return every value with exactly the same
  248. * probability, if the next()-method would be a perfect random number
  249. * generator.
  250. *
  251. * The loop at the bottom only accepts a value, if the random
  252. * number was between 0 and the highest number less then 1<<31,
  253. * which is divisible by n. The probability for this is high for small
  254. * n, and the worst case is 1/2 (for n=(1<<30)+1).
  255. *
  256. * The special treatment for n = power of 2, selects the high bits of
  257. * the random number (the loop at the bottom would select the low order
  258. * bits). This is done, because the low order bits of linear congruential
  259. * number generators (like the one used in this class) are known to be
  260. * ``less random'' than the high order bits.
  261. *
  262. * @param n the upper bound
  263. * @throws IllegalArgumentException if the given upper bound is negative
  264. * @return the next pseudorandom value
  265. * @since 1.2
  266. */
  267. public int nextInt(int n)
  268. {
  269. if (n <= 0)
  270. throw new IllegalArgumentException("n must be positive");
  271. if ((n & -n) == n) // i.e., n is a power of 2
  272. return (int) ((n * (long) next(31)) >> 31);
  273. int bits, val;
  274. do
  275. {
  276. bits = next(31);
  277. val = bits % n;
  278. }
  279. while (bits - val + (n - 1) < 0);
  280. return val;
  281. }
  282. /**
  283. * Generates the next pseudorandom long number. All bits of this
  284. * long are independently chosen and 0 and 1 have equal likelihood.
  285. * The implementation for java.util.Random is:
  286. *
  287. <pre>public long nextLong()
  288. {
  289. return ((long) next(32) &lt;&lt; 32) + next(32);
  290. }</pre>
  291. *
  292. * @return the next pseudorandom value
  293. */
  294. public long nextLong()
  295. {
  296. return ((long) next(32) << 32) + next(32);
  297. }
  298. /**
  299. * Generates the next pseudorandom boolean. True and false have
  300. * the same probability. The implementation is:
  301. *
  302. <pre>public boolean nextBoolean()
  303. {
  304. return next(1) != 0;
  305. }</pre>
  306. *
  307. * @return the next pseudorandom boolean
  308. * @since 1.2
  309. */
  310. public boolean nextBoolean()
  311. {
  312. return next(1) != 0;
  313. }
  314. /**
  315. * Generates the next pseudorandom float uniformly distributed
  316. * between 0.0f (inclusive) and 1.0f (exclusive). The
  317. * implementation is as follows.
  318. *
  319. <pre>public float nextFloat()
  320. {
  321. return next(24) / ((float)(1 &lt;&lt; 24));
  322. }</pre>
  323. *
  324. * @return the next pseudorandom float
  325. */
  326. public float nextFloat()
  327. {
  328. return next(24) / (float) (1 << 24);
  329. }
  330. /**
  331. * Generates the next pseudorandom double uniformly distributed
  332. * between 0.0 (inclusive) and 1.0 (exclusive). The
  333. * implementation is as follows.
  334. *
  335. <pre>public double nextDouble()
  336. {
  337. return (((long) next(26) &lt;&lt; 27) + next(27)) / (double)(1L &lt;&lt; 53);
  338. }</pre>
  339. *
  340. * @return the next pseudorandom double
  341. */
  342. public double nextDouble()
  343. {
  344. return (((long) next(26) << 27) + next(27)) / (double) (1L << 53);
  345. }
  346. /**
  347. * Generates the next pseudorandom, Gaussian (normally) distributed
  348. * double value, with mean 0.0 and standard deviation 1.0.
  349. * The algorithm is as follows.
  350. *
  351. <pre>public synchronized double nextGaussian()
  352. {
  353. if (haveNextNextGaussian)
  354. {
  355. haveNextNextGaussian = false;
  356. return nextNextGaussian;
  357. }
  358. else
  359. {
  360. double v1, v2, s;
  361. do
  362. {
  363. v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
  364. v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0
  365. s = v1 * v1 + v2 * v2;
  366. }
  367. while (s >= 1);
  368. double norm = Math.sqrt(-2 * Math.log(s) / s);
  369. nextNextGaussian = v2 * norm;
  370. haveNextNextGaussian = true;
  371. return v1 * norm;
  372. }
  373. }</pre>
  374. *
  375. * <p>This is described in section 3.4.1 of <em>The Art of Computer
  376. * Programming, Volume 2</em> by Donald Knuth.
  377. *
  378. * @return the next pseudorandom Gaussian distributed double
  379. */
  380. public synchronized double nextGaussian()
  381. {
  382. if (haveNextNextGaussian)
  383. {
  384. haveNextNextGaussian = false;
  385. return nextNextGaussian;
  386. }
  387. double v1, v2, s;
  388. do
  389. {
  390. v1 = 2 * nextDouble() - 1; // Between -1.0 and 1.0.
  391. v2 = 2 * nextDouble() - 1; // Between -1.0 and 1.0.
  392. s = v1 * v1 + v2 * v2;
  393. }
  394. while (s >= 1);
  395. double norm = Math.sqrt(-2 * Math.log(s) / s);
  396. nextNextGaussian = v2 * norm;
  397. haveNextNextGaussian = true;
  398. return v1 * norm;
  399. }
  400. }