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.statistics.distribution;
18  
19  import org.apache.commons.numbers.gamma.LogGamma;
20  import org.apache.commons.numbers.gamma.RegularizedGamma;
21  import org.apache.commons.rng.UniformRandomProvider;
22  import org.apache.commons.rng.sampling.distribution.AhrensDieterMarsagliaTsangGammaSampler;
23  
24  /**
25   * Implementation of the gamma distribution.
26   *
27   * <p>The probability density function of \( X \) is:
28   *
29   * <p>\[ f(x;k,\theta) = \frac{x^{k-1}e^{-x/\theta}}{\theta^k\Gamma(k)} \]
30   *
31   * <p>for \( k &gt; 0 \) the shape, \( \theta &gt; 0 \) the scale, \( \Gamma(k) \) is the gamma function
32   * and \( x \in (0, \infty) \).
33   *
34   * @see <a href="https://en.wikipedia.org/wiki/Gamma_distribution">Gamma distribution (Wikipedia)</a>
35   * @see <a href="https://mathworld.wolfram.com/GammaDistribution.html">Gamma distribution (MathWorld)</a>
36   */
37  public final class GammaDistribution extends AbstractContinuousDistribution {
38      /** Support lower bound. */
39      private static final double SUPPORT_LO = 0;
40      /** Support upper bound. */
41      private static final double SUPPORT_HI = Double.POSITIVE_INFINITY;
42  
43      /** The shape parameter. */
44      private final double shape;
45      /** The scale parameter. */
46      private final double scale;
47      /** Precomputed term for the log density: {@code -log(gamma(shape)) - log(scale)}. */
48      private final double minusLogGammaShapeMinusLogScale;
49      /** Cached value for inverse probability function. */
50      private final double mean;
51      /** Cached value for inverse probability function. */
52      private final double variance;
53  
54      /**
55       * @param shape Shape parameter.
56       * @param scale Scale parameter.
57       */
58      private GammaDistribution(double shape,
59                                double scale) {
60          this.shape = shape;
61          this.scale = scale;
62          this.minusLogGammaShapeMinusLogScale = -LogGamma.value(shape) - Math.log(scale);
63          mean = shape * scale;
64          variance = shape * scale * scale;
65      }
66  
67      /**
68       * Creates a gamma distribution.
69       *
70       * @param shape Shape parameter.
71       * @param scale Scale parameter.
72       * @return the distribution
73       * @throws IllegalArgumentException if {@code shape <= 0} or {@code scale <= 0}.
74       */
75      public static GammaDistribution of(double shape,
76                                         double scale) {
77          if (shape <= 0) {
78              throw new DistributionException(DistributionException.NOT_STRICTLY_POSITIVE, shape);
79          }
80          if (scale <= 0) {
81              throw new DistributionException(DistributionException.NOT_STRICTLY_POSITIVE, scale);
82          }
83          return new GammaDistribution(shape, scale);
84      }
85  
86      /**
87       * Gets the shape parameter of this distribution.
88       *
89       * @return the shape parameter.
90       */
91      public double getShape() {
92          return shape;
93      }
94  
95      /**
96       * Gets the scale parameter of this distribution.
97       *
98       * @return the scale parameter.
99       */
100     public double getScale() {
101         return scale;
102     }
103 
104     /** {@inheritDoc}
105      *
106      * <p>Returns the limit when {@code x = 0}:
107      * <ul>
108      * <li>{@code shape < 1}: Infinity
109      * <li>{@code shape == 1}: 1 / scale
110      * <li>{@code shape > 1}: 0
111      * </ul>
112      */
113     @Override
114     public double density(double x) {
115         if (x <= SUPPORT_LO ||
116             x >= SUPPORT_HI) {
117             // Special case x=0
118             if (x == SUPPORT_LO && shape <= 1) {
119                 return shape == 1 ?
120                     1 / scale :
121                     Double.POSITIVE_INFINITY;
122             }
123             return 0;
124         }
125 
126         return RegularizedGamma.P.derivative(shape, x / scale) / scale;
127     }
128 
129     /** {@inheritDoc}
130      *
131      * <p>Returns the limit when {@code x = 0}:
132      * <ul>
133      * <li>{@code shape < 1}: Infinity
134      * <li>{@code shape == 1}: -log(scale)
135      * <li>{@code shape > 1}: -Infinity
136      * </ul>
137      */
138     @Override
139     public double logDensity(double x) {
140         if (x <= SUPPORT_LO ||
141             x >= SUPPORT_HI) {
142             // Special case x=0
143             if (x == SUPPORT_LO && shape <= 1) {
144                 return shape == 1 ?
145                     -Math.log(scale) :
146                     Double.POSITIVE_INFINITY;
147             }
148             return Double.NEGATIVE_INFINITY;
149         }
150 
151         final double y = x / scale;
152 
153         // More accurate to log the density when it is finite.
154         // See NUMBERS-174: 'Log of the Gamma P Derivative'
155         final double p = RegularizedGamma.P.derivative(shape, y) / scale;
156         if (p <= Double.MAX_VALUE && p >= Double.MIN_NORMAL) {
157             return Math.log(p);
158         }
159         // Use the log computation
160         return minusLogGammaShapeMinusLogScale - y + Math.log(y) * (shape - 1);
161     }
162 
163     /** {@inheritDoc} */
164     @Override
165     public double cumulativeProbability(double x) {
166         if (x <= SUPPORT_LO) {
167             return 0;
168         } else if (x >= SUPPORT_HI) {
169             return 1;
170         }
171         return RegularizedGamma.P.value(shape, x / scale);
172     }
173 
174     /** {@inheritDoc} */
175     @Override
176     public double survivalProbability(double x) {
177         if (x <= SUPPORT_LO) {
178             return 1;
179         } else if (x >= SUPPORT_HI) {
180             return 0;
181         }
182         return RegularizedGamma.Q.value(shape, x / scale);
183     }
184 
185     /**
186      * {@inheritDoc}
187      *
188      * <p>For shape parameter \( k \) and scale parameter \( \theta \), the
189      * mean is \( k \theta \).
190      */
191     @Override
192     public double getMean() {
193         return mean;
194     }
195 
196     /**
197      * {@inheritDoc}
198      *
199      * <p>For shape parameter \( k \) and scale parameter \( \theta \), the
200      * variance is \( k \theta^2 \).
201      */
202     @Override
203     public double getVariance() {
204         return variance;
205     }
206 
207     /**
208      * {@inheritDoc}
209      *
210      * <p>The lower bound of the support is always 0.
211      *
212      * @return 0.
213      */
214     @Override
215     public double getSupportLowerBound() {
216         return SUPPORT_LO;
217     }
218 
219     /**
220      * {@inheritDoc}
221      *
222      * <p>The upper bound of the support is always positive infinity.
223      *
224      * @return {@linkplain Double#POSITIVE_INFINITY positive infinity}.
225      */
226     @Override
227     public double getSupportUpperBound() {
228         return SUPPORT_HI;
229     }
230 
231     /** {@inheritDoc} */
232     @Override
233     public ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng) {
234         // Gamma distribution sampler.
235         return AhrensDieterMarsagliaTsangGammaSampler.of(rng, shape, scale)::sample;
236     }
237 }