001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.math3.distribution;
018
019import org.apache.commons.math3.exception.OutOfRangeException;
020import org.apache.commons.math3.exception.util.LocalizedFormats;
021import org.apache.commons.math3.random.RandomGenerator;
022import org.apache.commons.math3.random.Well19937c;
023import org.apache.commons.math3.util.FastMath;
024
025/**
026 * Implementation of the geometric distribution.
027 *
028 * @see <a href="http://en.wikipedia.org/wiki/Geometric_distribution">Geometric distribution (Wikipedia)</a>
029 * @see <a href="http://mathworld.wolfram.com/GeometricDistribution.html">Geometric Distribution (MathWorld)</a>
030 * @since 3.3
031 */
032public class GeometricDistribution extends AbstractIntegerDistribution {
033
034    /** Serializable version identifier. */
035    private static final long serialVersionUID = 20130507L;
036    /** The probability of success. */
037    private final double probabilityOfSuccess;
038    /** {@code log(p)} where p is the probability of success. */
039    private final double logProbabilityOfSuccess;
040    /** {@code log(1 - p)} where p is the probability of success. */
041    private final double log1mProbabilityOfSuccess;
042
043    /**
044     * Create a geometric distribution with the given probability of success.
045     * <p>
046     * <b>Note:</b> this constructor will implicitly create an instance of
047     * {@link Well19937c} as random generator to be used for sampling only (see
048     * {@link #sample()} and {@link #sample(int)}). In case no sampling is
049     * needed for the created distribution, it is advised to pass {@code null}
050     * as random generator via the appropriate constructors to avoid the
051     * additional initialisation overhead.
052     *
053     * @param p probability of success.
054     * @throws OutOfRangeException if {@code p <= 0} or {@code p > 1}.
055     */
056    public GeometricDistribution(double p) {
057        this(new Well19937c(), p);
058    }
059
060    /**
061     * Creates a geometric distribution.
062     *
063     * @param rng Random number generator.
064     * @param p Probability of success.
065     * @throws OutOfRangeException if {@code p <= 0} or {@code p > 1}.
066     */
067    public GeometricDistribution(RandomGenerator rng, double p) {
068        super(rng);
069
070        if (p <= 0 || p > 1) {
071            throw new OutOfRangeException(LocalizedFormats.OUT_OF_RANGE_LEFT, p, 0, 1);
072        }
073
074        probabilityOfSuccess = p;
075        logProbabilityOfSuccess = FastMath.log(p);
076        log1mProbabilityOfSuccess = FastMath.log1p(-p);
077    }
078
079    /**
080     * Access the probability of success for this distribution.
081     *
082     * @return the probability of success.
083     */
084    public double getProbabilityOfSuccess() {
085        return probabilityOfSuccess;
086    }
087
088    /** {@inheritDoc} */
089    public double probability(int x) {
090        if (x < 0) {
091            return 0.0;
092        } else {
093            return FastMath.exp(log1mProbabilityOfSuccess * x) * probabilityOfSuccess;
094        }
095    }
096
097    /** {@inheritDoc} */
098    @Override
099    public double logProbability(int x) {
100        if (x < 0) {
101            return Double.NEGATIVE_INFINITY;
102        } else {
103            return x * log1mProbabilityOfSuccess + logProbabilityOfSuccess;
104        }
105    }
106
107    /** {@inheritDoc} */
108    public double cumulativeProbability(int x) {
109        if (x < 0) {
110            return 0.0;
111        } else {
112            return -FastMath.expm1(log1mProbabilityOfSuccess * (x + 1));
113        }
114    }
115
116    /**
117     * {@inheritDoc}
118     *
119     * For probability parameter {@code p}, the mean is {@code (1 - p) / p}.
120     */
121    public double getNumericalMean() {
122        return (1 - probabilityOfSuccess) / probabilityOfSuccess;
123    }
124
125    /**
126     * {@inheritDoc}
127     *
128     * For probability parameter {@code p}, the variance is
129     * {@code (1 - p) / (p * p)}.
130     */
131    public double getNumericalVariance() {
132        return (1 - probabilityOfSuccess) / (probabilityOfSuccess * probabilityOfSuccess);
133    }
134
135    /**
136     * {@inheritDoc}
137     *
138     * The lower bound of the support is always 0.
139     *
140     * @return lower bound of the support (always 0)
141     */
142    public int getSupportLowerBound() {
143        return 0;
144    }
145
146    /**
147     * {@inheritDoc}
148     *
149     * The upper bound of the support is infinite (which we approximate as
150     * {@code Integer.MAX_VALUE}).
151     *
152     * @return upper bound of the support (always Integer.MAX_VALUE)
153     */
154    public int getSupportUpperBound() {
155        return Integer.MAX_VALUE;
156    }
157
158    /**
159     * {@inheritDoc}
160     *
161     * The support of this distribution is connected.
162     *
163     * @return {@code true}
164     */
165    public boolean isSupportConnected() {
166        return true;
167    }
168
169    /**
170     * {@inheritDoc}
171     */
172    @Override
173    public int inverseCumulativeProbability(double p) throws OutOfRangeException {
174        if (p < 0 || p > 1) {
175            throw new OutOfRangeException(p, 0, 1);
176        }
177        if (p == 1) {
178            return Integer.MAX_VALUE;
179        }
180        if (p == 0) {
181            return 0;
182        }
183        return Math.max(0, (int) Math.ceil(FastMath.log1p(-p)/log1mProbabilityOfSuccess-1));
184    }
185}