View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.rng.sampling.distribution;
18  
19  import org.apache.commons.rng.UniformRandomProvider;
20  
21  /**
22   * Sampler for the <a href="http://mathworld.wolfram.com/PoissonDistribution.html">Poisson distribution</a>.
23   *
24   * <ul>
25   *  <li>
26   *   For small means, a Poisson process is simulated using uniform deviates, as
27   *   described <a href="http://mathaa.epfl.ch/cours/PMMI2001/interactive/rng7.htm">here</a>.
28   *   The Poisson process (and hence, the returned value) is bounded by 1000 * mean.
29   *  </li>
30   *  <li>
31   *   For large means, we use the rejection algorithm described in
32   *   <blockquote>
33   *    Devroye, Luc. (1981). <i>The Computer Generation of Poisson Random Variables</i><br>
34   *    <strong>Computing</strong> vol. 26 pp. 197-207.
35   *   </blockquote>
36   *  </li>
37   * </ul>
38   *
39   * @since 1.0
40   */
41  public class PoissonSampler
42      extends SamplerBase
43      implements DiscreteSampler {
44  
45      /** Value for switching sampling algorithm. */
46      private static final double PIVOT = 40;
47      /** The internal Poisson sampler. */
48      private final DiscreteSampler poissonSampler;
49  
50      /**
51       * @param rng Generator of uniformly distributed random numbers.
52       * @param mean Mean.
53       * @throws IllegalArgumentException if {@code mean <= 0}.
54       */
55      public PoissonSampler(UniformRandomProvider rng,
56                            double mean) {
57          super(null);
58  
59          // Delegate all work to specialised samplers.
60          // These should check the input arguments.
61          poissonSampler = mean < PIVOT ?
62              new SmallMeanPoissonSampler(rng, mean) :
63              new LargeMeanPoissonSampler(rng, mean);
64      }
65  
66      /** {@inheritDoc} */
67      @Override
68      public int sample() {
69          return poissonSampler.sample();
70      }
71  
72      /** {@inheritDoc} */
73      @Override
74      public String toString() {
75          return poissonSampler.toString();
76      }
77  }