1 package nl.tudelft.simulation.jstats.distributions;
2
3 import org.djutils.exceptions.Throw;
4
5 import nl.tudelft.simulation.jstats.streams.StreamInterface;
6
7 /**
8 * The Geometric distribution. The geometric distribution is the only discrete memoryless random distribution. It is a discrete
9 * analog of the exponential distribution. There are two variants, one that indicates the number of Bernoulli trials to get the
10 * first success (1, 2, 3, ...), and one that indicates the number of failures before the first success (0, 1, 2, ...). In line
11 * with Law & Kelton, the version of the number of failures before the first success is modeled here, so X ={0, 1, 2, ...}.
12 * For more information on this distribution see <a href="https://mathworld.wolfram.com/GeometricDistribution.html">
13 * https://mathworld.wolfram.com/GeometricDistribution.html </a>
14 * <p>
15 * Copyright (c) 2002-2025 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
16 * for project information <a href="https://simulation.tudelft.nl/dsol/manual/" target="_blank">DSOL Manual</a>. The DSOL
17 * project is distributed under a three-clause BSD-style license, which can be found at
18 * <a href="https://simulation.tudelft.nl/dsol/docs/latest/license.html" target="_blank">DSOL License</a>.
19 * </p>
20 * @author <a href="https://www.linkedin.com/in/peterhmjacobs">Peter Jacobs </a>
21 * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
22 */
23 public class DistGeometric extends DistDiscrete
24 {
25 /** p is the the probability of success for each individual trial. */
26 private final double p;
27
28 /** lnp is a helper variable with value ln(1-p) to avoid repetitive calculation. */
29 private final double lnp;
30
31 /**
32 * Construct a new geometric distribution for a repeated set of Bernoulli trials, indicating the number of failures before
33 * the first success.
34 * @param stream the random number stream
35 * @param p the probability of success for each individual trial
36 * @throws IllegalArgumentException when p <= 0 or p >= 1
37 */
38 public DistGeometric(final StreamInterface stream, final double p)
39 {
40 super(stream);
41 Throw.when(p <= 0.0 || p >= 1.0, IllegalArgumentException.class, "Error Geometric - p <= 0 or p >= 1");
42 this.p = p;
43 this.lnp = Math.log(1.0 - this.p);
44 }
45
46 @Override
47 public long draw()
48 {
49 double u = this.stream.nextDouble();
50 return (long) (Math.floor(Math.log(u) / this.lnp));
51 }
52
53 @Override
54 public double probability(final long observation)
55 {
56 if (observation >= 0)
57 {
58 return this.p * Math.pow(1 - this.p, observation);
59 }
60 return 0.0;
61 }
62
63 /**
64 * Return the probability of success for each individual trial.
65 * @return the probability of success for each individual trial
66 */
67 public double getP()
68 {
69 return this.p;
70 }
71
72 @Override
73 public String toString()
74 {
75 return "Geometric(" + this.p + ")";
76 }
77 }