1 package nl.tudelft.simulation.jstats.distributions;
2
3 import org.djutils.exceptions.Throw;
4
5 import nl.tudelft.simulation.jstats.math.ProbMath;
6 import nl.tudelft.simulation.jstats.streams.StreamInterface;
7
8 /**
9 * The Poisson distribution. For more information on this distribution see
10 * <a href="https://mathworld.wolfram.com/PoissonDistribution.html"> https://mathworld.wolfram.com/PoissonDistribution.html </a>
11 * <p>
12 * Copyright (c) 2002-2025 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
13 * for project information <a href="https://simulation.tudelft.nl/dsol/manual/" target="_blank">DSOL Manual</a>. The DSOL
14 * project is distributed under a three-clause BSD-style license, which can be found at
15 * <a href="https://simulation.tudelft.nl/dsol/docs/latest/license.html" target="_blank">DSOL License</a>.
16 * </p>
17 * @author <a href="https://www.linkedin.com/in/peterhmjacobs">Peter Jacobs </a>
18 * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
19 */
20 public class DistPoisson extends DistDiscrete
21 {
22 /** lambda is the lambda parameter. */
23 private final double lambda;
24
25 /** expl is a helper variable. */
26 private final double expl;
27
28 /**
29 * constructs a new Poisson distribution.
30 * @param stream the random number stream
31 * @param lambda the lambda parameter
32 * @throws IllegalArgumentException when lambda <= 0
33 */
34 public DistPoisson(final StreamInterface stream, final double lambda)
35 {
36 super(stream);
37 Throw.when(lambda <= 0.0, IllegalArgumentException.class, "Error Poisson - lambda<=0");
38 this.lambda = lambda;
39 this.expl = Math.exp(-this.lambda);
40 }
41
42 @Override
43 public long draw()
44 {
45 // Adapted from Fortran program in Shannon, Systems Simulation, 1975, p. 359
46 double s = 1.0;
47 long x = -1;
48 do
49 {
50 s = s * this.stream.nextDouble();
51 x++;
52 }
53 while (s > this.expl);
54 return x;
55 }
56
57 @Override
58 public double probability(final long observation)
59 {
60 if (observation >= 0)
61 {
62 return (Math.exp(-this.lambda) * Math.pow(this.lambda, observation)) / ProbMath.factorial(observation);
63 }
64 return 0;
65 }
66
67 /**
68 * @return lambda
69 */
70 public double getLambda()
71 {
72 return this.lambda;
73 }
74
75 @Override
76 public String toString()
77 {
78 return "Poisson(" + this.lambda + ")";
79 }
80 }