001/*
002 * RandomPoissonDistribution.java
003 * Copyright (c) 2002 
004 *
005 * This program is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU General Public License
007 * as published by the Free Software Foundation; either version 2
008 * of the License, or any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU General Public License for more details.
014 *
015 * You should have received a copy of the GNU General Public License
016 * along with this program; if not, write to the Free Software
017 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
018 */
019
020package ca.bc.webarts.widgets.random;
021
022import java.util.Random;
023
024/**
025 *  A generator of random numbers with Poisson distribution.
026 * (C) 2000, Laurentiu Cristofor (laur72_98@yahoo.com)
027 *  
028 *
029 * @created    May 19, 2002
030 */
031
032public class RandomPoissonDistribution
033{
034  private Random rand;
035  private long mean;
036
037
038  /**
039   *  Create a new generator of random numbers with Poisson distribution of
040   *  specified mean.
041   *
042   * @param  mean  the mean of the Poisson distribution
043   */
044  public RandomPoissonDistribution(long mean)
045  {
046    this.mean = mean;
047    rand = new Random();
048  }
049
050
051  /**
052   *  Return a random number with Poisson distribution.
053   *
054   * @return    Description of the Return Value
055   */
056  public long nextLong()
057  {
058    // See Knuth, TAOCP, vol. 2, second print
059    // section 3.4.1, algorithm Q on page 117
060    // Q1. [Calculate exponential]
061    double p = Math.exp(-(double) mean);
062    long N = 0;
063    double q = 1.0;
064
065    while (true)
066    {
067      // Q2. [Get uniform variable]
068      double U = rand.nextDouble();
069      // Q3. [Multiply]
070      q = q * U;
071      // Q4. [Test]
072      if (q >= p)
073      {
074        N = N + 1;
075      }
076      else
077      {
078        return N;
079      }
080    }
081  }
082
083
084  /**
085   *  The main program for the RandomPoissonDistribution class
086   *
087   * @param  args  The command line arguments
088   */
089  public static void main(String[] args)
090  {
091    RandomPoissonDistribution poisson
092         = new RandomPoissonDistribution(10);
093
094    for (int i = 0; i <= 10; i++)
095    {
096      System.out.println(poisson.nextLong());
097    }
098  }
099}
100
101