package umontreal.iro.lecuyer.randvar;
import umontreal.iro.lecuyer.probdist.*;
import umontreal.iro.lecuyer.rng.*;

/**
 * Implements binomial random variate generators using the 
 * convolution method.  
 * This method generates n Bernouilli random variates with 
 * parameter p and adds them up. 
 * Its advantages are that it requires
 * little computer memory and no setup time.
 * Its disadvantage is that it is very slow for large n.
 * It makes sense only when n is small.
 * 
 */
public class BinomialConvolutionGen extends BinomialGen  {
  


   /**
    * Creates a binomial random variate generator with
    *   parameters n and p, using stream s.
    * 
    */
   public BinomialConvolutionGen (RandomStream s, int n, double p) {
      super (s, null);
      setParams (n, p);
   }


   /**
    * Creates a random variate generator for the binomial
    *    distribution dist and stream s.
    * 
    */
   public BinomialConvolutionGen (RandomStream s, BinomialDist dist)  {
      super (s, dist);
   }


   public int nextInt() { 
      int x = 0;
      for (int i = 0; i < n; i++) {
         double unif = stream.nextDouble();
         if (unif <= p)
            x++;
      }
      return x;
   }

   public static int nextInt (RandomStream s, int n, double p) {
      if (n <= 0)
         throw new IllegalArgumentException ("n <= 0");
      if (p < 0 || p > 1)
         throw new IllegalArgumentException ("p must be in [0,1]");
      return convolution (s, n, p);
   }
   /**
    * Generates a new integer from the binomial distribution with parameters
    *    n = n and p = p, using the given stream s.
    * 
    */


   private static int convolution (RandomStream stream, int n, double p) {
      int x = 0;
      for (int i = 0; i < n; i++) {
         double unif = stream.nextDouble();
         if (unif <= p)
            x++;
      }
      return x;
   }
}

 

Ads help maintain this website.