home *** CD-ROM | disk | FTP | other *** search
/ PC Online 1998 January / PCO0198.ISO / 1&1 / java.z / java_301 / java / util / Random.class (.txt) < prev    next >
Encoding:
Java Class File  |  1996-10-20  |  1.8 KB  |  70 lines

  1. package java.util;
  2.  
  3. public class Random {
  4.    private long seed;
  5.    private static final long multiplier = 25214903917L;
  6.    private static final long addend = 11L;
  7.    private static final long mask = (1L << 48) - 1L;
  8.    private double nextNextGaussian;
  9.    private boolean haveNextNextGaussian;
  10.  
  11.    public Random() {
  12.       this(System.currentTimeMillis());
  13.    }
  14.  
  15.    public Random(long seed) {
  16.       this.haveNextNextGaussian = false;
  17.       this.setSeed(seed);
  18.       this.haveNextNextGaussian = false;
  19.    }
  20.  
  21.    public synchronized void setSeed(long seed) {
  22.       this.seed = (seed ^ 25214903917L) & mask;
  23.    }
  24.  
  25.    private synchronized int next(int bits) {
  26.       long nextseed = this.seed * 25214903917L + 11L & mask;
  27.       this.seed = nextseed;
  28.       return (int)(nextseed >>> 48 - bits);
  29.    }
  30.  
  31.    public int nextInt() {
  32.       return this.next(32);
  33.    }
  34.  
  35.    public long nextLong() {
  36.       return ((long)this.next(32) << 32) + (long)this.next(32);
  37.    }
  38.  
  39.    public float nextFloat() {
  40.       int i = this.next(30);
  41.       return (float)i / 1.0737418E9F;
  42.    }
  43.  
  44.    public double nextDouble() {
  45.       long l = ((long)this.next(27) << 27) + (long)this.next(27);
  46.       return (double)l / (double)(1L << 54);
  47.    }
  48.  
  49.    public synchronized double nextGaussian() {
  50.       if (this.haveNextNextGaussian) {
  51.          this.haveNextNextGaussian = false;
  52.          return this.nextNextGaussian;
  53.       } else {
  54.          double v1;
  55.          double v2;
  56.          double s;
  57.          do {
  58.             v1 = (double)2.0F * this.nextDouble() - (double)1.0F;
  59.             v2 = (double)2.0F * this.nextDouble() - (double)1.0F;
  60.             s = v1 * v1 + v2 * v2;
  61.          } while(s >= (double)1.0F);
  62.  
  63.          double multiplier = Math.sqrt((double)-2.0F * Math.log(s) / s);
  64.          this.nextNextGaussian = v2 * multiplier;
  65.          this.haveNextNextGaussian = true;
  66.          return v1 * multiplier;
  67.       }
  68.    }
  69. }
  70.