package umontreal.iro.lecuyer.rng;

import umontreal.iro.lecuyer.rng.RandomStream;


/**
 * Represents a container random stream generating numbers in an interval 
 * (a, b) instead of in (0, 1), where 
 * 0 <= a < b <= 1, 
 * by using the contained stream.
 * If nextDouble returns u for the contained stream,
 * it will return 
 * v = a + (b - a)u, which is uniform over (a, b),
 * for the truncated stream.
 * The method nextInt returns the integer that corresponds to v
 * (by inversion); this integer is no longer uniformly distributed in general.
 * 
 */
public class TruncatedRandomStream implements RandomStream {
   private RandomStream stream;
   private double a;
   private double bminusa;



   public TruncatedRandomStream (RandomStream stream, double a, double b) {
      if (stream == null)
         throw new NullPointerException ("The given stream must not be null");
      if (a >= b)
         throw new IllegalArgumentException ("a must be smaller than b");
      if (a < 0 || b < 0 || a > 1 || b > 1)
         throw new IllegalArgumentException ("a and b must be in [0, 1]");
      this.stream = stream;
      this.a = a;
      bminusa = b - a;
   }

   public void resetStartStream () {
      stream.resetStartStream ();
   }

   public void resetStartSubstream () {
      stream.resetStartSubstream ();
   }

   public void resetNextSubstream () {
      stream.resetNextSubstream ();
   }

   public double nextDouble () {
      double v = stream.nextDouble ();
      return a + v * bminusa;
   }

   public void nextArrayOfDouble (double[] u, int start, int n) {
      stream.nextArrayOfDouble (u, start, n);
      for (int i = start; i < start + n; i++)
         u[i] = a + u[i] * bminusa;
   }

   public int nextInt (int i, int j) {
      return i + (int) (nextDouble () * (j - i + 1));
   }

   public void nextArrayOfInt (int i, int j, int[] u, int start, int n) {
      for (int x = start; x < start + n; x++)
         u[x] = nextInt (i, j);
   }
}

 

Ads help maintain this website.