001: /*
002: *
003: *
004: * Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved.
005: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
006: *
007: * This program is free software; you can redistribute it and/or
008: * modify it under the terms of the GNU General Public License version
009: * 2 only, as published by the Free Software Foundation.
010: *
011: * This program is distributed in the hope that it will be useful, but
012: * WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014: * General Public License version 2 for more details (a copy is
015: * included at /legal/license.txt).
016: *
017: * You should have received a copy of the GNU General Public License
018: * version 2 along with this work; if not, write to the Free Software
019: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
020: * 02110-1301 USA
021: *
022: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
023: * Clara, CA 95054 or visit www.sun.com if you need additional
024: * information or have any questions.
025: */
026:
027: package java.util;
028:
029: /**
030: * An instance of this class is used to generate a stream of
031: * pseudorandom numbers. The class uses a 48-bit seed, which is
032: * modified using a linear congruential formula. (See Donald Knuth,
033: * <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
034: * <p>
035: * If two instances of <code>Random</code> are created with the same
036: * seed, and the same sequence of method calls is made for each, they
037: * will generate and return identical sequences of numbers. In order to
038: * guarantee this property, particular algorithms are specified for the
039: * class <tt>Random</tt>. Java implementations must use all the algorithms
040: * shown here for the class <tt>Random</tt>, for the sake of absolute
041: * portability of Java code. However, subclasses of class <tt>Random</tt>
042: * are permitted to use other algorithms, so long as they adhere to the
043: * general contracts for all the methods.
044: * <p>
045: * The algorithms implemented by class <tt>Random</tt> use a
046: * <tt>protected</tt> utility method that on each invocation can supply
047: * up to 32 pseudorandomly generated bits.
048: * <p>
049: *
050: * @version 12/17/01 (CLDC 1.1)
051: * @since JDK1.0, CLDC 1.0
052: */
053: public class Random {
054:
055: /**
056: * The internal state associated with this pseudorandom number generator.
057: * (The specs for the methods in this class describe the ongoing
058: * computation of this value.)
059: */
060: private long seed;
061:
062: private final static long multiplier = 0x5DEECE66DL;
063: private final static long addend = 0xBL;
064: private final static long mask = (1L << 48) - 1;
065:
066: /**
067: * Creates a new random number generator. Its seed is initialized to
068: * a value based on the current time:
069: * <blockquote><pre>
070: * public Random() { this(System.currentTimeMillis()); }</pre></blockquote>
071: *
072: * @see java.lang.System#currentTimeMillis()
073: */
074: public Random() {
075: this (System.currentTimeMillis());
076: }
077:
078: /**
079: * Creates a new random number generator using a single
080: * <code>long</code> seed:
081: * <blockquote><pre>
082: * public Random(long seed) { setSeed(seed); }</pre></blockquote>
083: * Used by method <tt>next</tt> to hold
084: * the state of the pseudorandom number generator.
085: *
086: * @param seed the initial seed.
087: * @see java.util.Random#setSeed(long)
088: */
089: public Random(long seed) {
090: setSeed(seed);
091: }
092:
093: /**
094: * Sets the seed of this random number generator using a single
095: * <code>long</code> seed. The general contract of <tt>setSeed</tt>
096: * is that it alters the state of this random number generator
097: * object so as to be in exactly the same state as if it had just
098: * been created with the argument <tt>seed</tt> as a seed. The method
099: * <tt>setSeed</tt> is implemented by class Random as follows:
100: * <blockquote><pre>
101: * synchronized public void setSeed(long seed) {
102: * this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);
103: * }</pre></blockquote>
104: * The implementation of <tt>setSeed</tt> by class <tt>Random</tt>
105: * happens to use only 48 bits of the given seed. In general, however,
106: * an overriding method may use all 64 bits of the long argument
107: * as a seed value.
108: *
109: * @param seed the initial seed.
110: */
111: synchronized public void setSeed(long seed) {
112: this .seed = (seed ^ multiplier) & mask;
113: }
114:
115: /**
116: * Generates the next pseudorandom number. Subclass should
117: * override this, as this is used by all other methods.<p>
118: * The general contract of <tt>next</tt> is that it returns an
119: * <tt>int</tt> value and if the argument bits is between <tt>1</tt>
120: * and <tt>32</tt> (inclusive), then that many low-order bits of the
121: * returned value will be (approximately) independently chosen bit
122: * values, each of which is (approximately) equally likely to be
123: * <tt>0</tt> or <tt>1</tt>. The method <tt>next</tt> is implemented
124: * by class <tt>Random</tt> as follows:
125: * <blockquote><pre>
126: * synchronized protected int next(int bits) {
127: * seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
128: * return (int)(seed >>> (48 - bits));
129: * }</pre></blockquote>
130: * This is a linear congruential pseudorandom number generator, as
131: * defined by D. H. Lehmer and described by Donald E. Knuth in <i>The
132: * Art of Computer Programming,</i> Volume 2: <i>Seminumerical
133: * Algorithms</i>, section 3.2.1.
134: *
135: * @param bits random bits
136: * @return the next pseudorandom value from this random number generator's sequence.
137: */
138: synchronized protected int next(int bits) {
139: long nextseed = (seed * multiplier + addend) & mask;
140: seed = nextseed;
141: return (int) (nextseed >>> (48 - bits));
142: }
143:
144: private static final int BITS_PER_BYTE = 8;
145:
146: /**
147: * Returns the next pseudorandom, uniformly distributed <code>int</code>
148: * value from this random number generator's sequence. The general
149: * contract of <tt>nextInt</tt> is that one <tt>int</tt> value is
150: * pseudorandomly generated and returned. All 2<font size="-1"><sup>32
151: * </sup></font> possible <tt>int</tt> values are produced with
152: * (approximately) equal probability. The method <tt>nextInt</tt> is
153: * implemented by class <tt>Random</tt> as follows:
154: * <blockquote><pre>
155: * public int nextInt() { return next(32); }</pre></blockquote>
156: *
157: * @return the next pseudorandom, uniformly distributed <code>int</code>
158: * value from this random number generator's sequence.
159: */
160: public int nextInt() {
161: return next(32);
162: }
163:
164: /**
165: * Returns a pseudorandom, uniformly distributed <tt>int</tt> value
166: * between 0 (inclusive) and the specified value (exclusive), drawn from
167: * this random number generator's sequence. The general contract of
168: * <tt>nextInt</tt> is that one <tt>int</tt> value in the specified range
169: * is pseudorandomly generated and returned. All <tt>n</tt> possible
170: * <tt>int</tt> values are produced with (approximately) equal
171: * probability. The method <tt>nextInt(int n)</tt> is implemented by
172: * class <tt>Random</tt> as follows:
173: * <blockquote><pre>
174: * public int nextInt(int n) {
175: * if (n<=0)
176: * throw new IllegalArgumentException("n must be positive");
177: *
178: * if ((n & -n) == n) // i.e., n is a power of 2
179: * return (int)((n * (long)next(31)) >> 31);
180: *
181: * int bits, val;
182: * do {
183: * bits = next(31);
184: * val = bits % n;
185: * } while(bits - val + (n-1) < 0);
186: * return val;
187: * }
188: * </pre></blockquote>
189: * <p>
190: * The hedge "approximately" is used in the foregoing description only
191: * because the next method is only approximately an unbiased source of
192: * independently chosen bits. If it were a perfect source of randomly
193: * chosen bits, then the algorithm shown would choose <tt>int</tt>
194: * values from the stated range with perfect uniformity.
195: * <p>
196: * The algorithm rejects values that would result
197: * in an uneven distribution (due to the fact that 2^31 is not divisible
198: * by n). The probability of a value being rejected depends on n. The
199: * worst case is n=2^30+1, for which the probability of a reject is 1/2,
200: * and the expected number of iterations before the loop terminates is 2.
201: * <p>
202: * The algorithm treats the case where n is a power of two specially: it
203: * returns the correct number of high-order bits from the underlying
204: * pseudo-random number generator. In the absence of special treatment,
205: * the correct number of <i>low-order</i> bits would be returned. Linear
206: * congruential pseudo-random number generators such as the one
207: * implemented by this class are known to have short periods in the
208: * sequence of values of their low-order bits. Thus, this special case
209: * greatly increases the length of the sequence of values returned by
210: * successive calls to this method if n is a small power of two.
211: *
212: * @param n the bound on the random number to be returned. Must be
213: * positive.
214: * @return a pseudorandom, uniformly distributed <tt>int</tt>
215: * value between 0 (inclusive) and n (exclusive).
216: * @exception IllegalArgumentException n is not positive.
217: * @since CLDC 1.1
218: */
219: public int nextInt(int n) {
220: if (n <= 0) {
221: throw new IllegalArgumentException(
222: /* #ifdef VERBOSE_EXCEPTIONS */
223: /// skipped "n must be positive"
224: /* #endif */
225: );
226: }
227: if ((n & -n) == n) // i.e., n is a power of 2
228: return (int) ((n * (long) next(31)) >> 31);
229:
230: int bits, val;
231: do {
232: bits = next(31);
233: val = bits % n;
234: } while (bits - val + (n - 1) < 0);
235: return val;
236: }
237:
238: /**
239: * Returns the next pseudorandom, uniformly distributed <code>long</code>
240: * value from this random number generator's sequence. The general
241: * contract of <tt>nextLong</tt> is that one long value is pseudorandomly
242: * generated and returned. All 2<font size="-1"><sup>64</sup></font>
243: * possible <tt>long</tt> values are produced with (approximately) equal
244: * probability. The method <tt>nextLong</tt> is implemented by class
245: * <tt>Random</tt> as follows:
246: * <blockquote><pre>
247: * public long nextLong() {
248: * return ((long)next(32) << 32) + next(32);
249: * }</pre></blockquote>
250: *
251: * @return the next pseudorandom, uniformly distributed <code>long</code>
252: * value from this random number generator's sequence.
253: */
254: public long nextLong() {
255: // it's okay that the bottom word remains signed.
256: return ((long) (next(32)) << 32) + next(32);
257: }
258:
259: /**
260: * Returns the next pseudorandom, uniformly distributed <code>float</code>
261: * value between <code>0.0</code> and <code>1.0</code> from this random
262: * number generator's sequence. <p>
263: * The general contract of <tt>nextFloat</tt> is that one <tt>float</tt>
264: * value, chosen (approximately) uniformly from the range <tt>0.0f</tt>
265: * (inclusive) to <tt>1.0f</tt> (exclusive), is pseudorandomly
266: * generated and returned. All 2<font size="-1"><sup>24</sup></font>
267: * possible <tt>float</tt> values of the form
268: * <i>m x </i>2<font size="-1"><sup>-24</sup></font>, where
269: * <i>m</i> is a positive integer less than 2<font size="-1"><sup>24</sup>
270: * </font>, are produced with (approximately) equal probability. The
271: * method <tt>nextFloat</tt> is implemented by class <tt>Random</tt> as
272: * follows:
273: * <blockquote><pre>
274: * public float nextFloat() {
275: * return next(24) / ((float)(1 << 24));
276: * }</pre></blockquote>
277: * The hedge "approximately" is used in the foregoing description only
278: * because the next method is only approximately an unbiased source of
279: * independently chosen bits. If it were a perfect source or randomly
280: * chosen bits, then the algorithm shown would choose <tt>float</tt>
281: * values from the stated range with perfect uniformity.<p>
282: * [In early versions of Java, the result was incorrectly calculated as:
283: * <blockquote><pre>
284: * return next(30) / ((float)(1 << 30));</pre></blockquote>
285: * This might seem to be equivalent, if not better, but in fact it
286: * introduced a slight nonuniformity because of the bias in the rounding
287: * of floating-point numbers: it was slightly more likely that the
288: * low-order bit of the significand would be 0 than that it would be 1.]
289: *
290: * @return the next pseudorandom, uniformly distributed <code>float</code>
291: * value between <code>0.0</code> and <code>1.0</code> from this
292: * random number generator's sequence.
293: * @since CLDC 1.1
294: */
295: public float nextFloat() {
296: int i = next(24);
297: return i / ((float) (1 << 24));
298: }
299:
300: /**
301: * Returns the next pseudorandom, uniformly distributed
302: * <code>double</code> value between <code>0.0</code> and
303: * <code>1.0</code> from this random number generator's sequence. <p>
304: * The general contract of <tt>nextDouble</tt> is that one
305: * <tt>double</tt> value, chosen (approximately) uniformly from the
306: * range <tt>0.0d</tt> (inclusive) to <tt>1.0d</tt> (exclusive), is
307: * pseudorandomly generated and returned. All
308: * 2<font size="-1"><sup>53</sup></font> possible <tt>float</tt>
309: * values of the form <i>m x </i>2<font size="-1"><sup>-53</sup>
310: * </font>, where <i>m</i> is a positive integer less than
311: * 2<font size="-1"><sup>53</sup></font>, are produced with
312: * (approximately) equal probability. The method <tt>nextDouble</tt> is
313: * implemented by class <tt>Random</tt> as follows:
314: * <blockquote><pre>
315: * public double nextDouble() {
316: * return (((long)next(26) << 27) + next(27))
317: * / (double)(1L << 53);
318: * }</pre></blockquote><p>
319: * The hedge "approximately" is used in the foregoing description only
320: * because the <tt>next</tt> method is only approximately an unbiased
321: * source of independently chosen bits. If it were a perfect source or
322: * randomly chosen bits, then the algorithm shown would choose
323: * <tt>double</tt> values from the stated range with perfect uniformity.
324: * <p>[In early versions of Java, the result was incorrectly calculated as:
325: * <blockquote><pre>
326: * return (((long)next(27) << 27) + next(27))
327: * / (double)(1L << 54);</pre></blockquote>
328: * This might seem to be equivalent, if not better, but in fact it
329: * introduced a large nonuniformity because of the bias in the rounding
330: * of floating-point numbers: it was three times as likely that the
331: * low-order bit of the significand would be 0 than that it would be
332: * 1! This nonuniformity probably doesn't matter much in practice, but
333: * we strive for perfection.]
334: *
335: * @return the next pseudorandom, uniformly distributed
336: * <code>double</code> value between <code>0.0</code> and
337: * <code>1.0</code> from this random number generator's sequence.
338: * @since CLDC 1.1
339: */
340: public double nextDouble() {
341: long l = ((long) (next(26)) << 27) + next(27);
342: return l / (double) (1L << 53);
343: }
344:
345: }
|