home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / 3rdParty / jbuilder / unsupported / JDK1.2beta3 / SOURCE / SRC.ZIP / java / util / Random.java < prev    next >
Encoding:
Java Source  |  1998-03-20  |  14.9 KB  |  343 lines

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