ExponentialDistribution.java

  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.math3.distribution;

  18. import org.apache.commons.math3.exception.NotStrictlyPositiveException;
  19. import org.apache.commons.math3.exception.OutOfRangeException;
  20. import org.apache.commons.math3.exception.util.LocalizedFormats;
  21. import org.apache.commons.math3.random.RandomGenerator;
  22. import org.apache.commons.math3.random.Well19937c;
  23. import org.apache.commons.math3.util.CombinatoricsUtils;
  24. import org.apache.commons.math3.util.FastMath;
  25. import org.apache.commons.math3.util.ResizableDoubleArray;

  26. /**
  27.  * Implementation of the exponential distribution.
  28.  *
  29.  * @see <a href="http://en.wikipedia.org/wiki/Exponential_distribution">Exponential distribution (Wikipedia)</a>
  30.  * @see <a href="http://mathworld.wolfram.com/ExponentialDistribution.html">Exponential distribution (MathWorld)</a>
  31.  */
  32. public class ExponentialDistribution extends AbstractRealDistribution {
  33.     /**
  34.      * Default inverse cumulative probability accuracy.
  35.      * @since 2.1
  36.      */
  37.     public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
  38.     /** Serializable version identifier */
  39.     private static final long serialVersionUID = 2401296428283614780L;
  40.     /**
  41.      * Used when generating Exponential samples.
  42.      * Table containing the constants
  43.      * q_i = sum_{j=1}^i (ln 2)^j/j! = ln 2 + (ln 2)^2/2 + ... + (ln 2)^i/i!
  44.      * until the largest representable fraction below 1 is exceeded.
  45.      *
  46.      * Note that
  47.      * 1 = 2 - 1 = exp(ln 2) - 1 = sum_{n=1}^infty (ln 2)^n / n!
  48.      * thus q_i -> 1 as i -> +inf,
  49.      * so the higher i, the closer to one we get (the series is not alternating).
  50.      *
  51.      * By trying, n = 16 in Java is enough to reach 1.0.
  52.      */
  53.     private static final double[] EXPONENTIAL_SA_QI;
  54.     /** The mean of this distribution. */
  55.     private final double mean;
  56.     /** The logarithm of the mean, stored to reduce computing time. **/
  57.     private final double logMean;
  58.     /** Inverse cumulative probability accuracy. */
  59.     private final double solverAbsoluteAccuracy;

  60.     /**
  61.      * Initialize tables.
  62.      */
  63.     static {
  64.         /**
  65.          * Filling EXPONENTIAL_SA_QI table.
  66.          * Note that we don't want qi = 0 in the table.
  67.          */
  68.         final double LN2 = FastMath.log(2);
  69.         double qi = 0;
  70.         int i = 1;

  71.         /**
  72.          * ArithmeticUtils provides factorials up to 20, so let's use that
  73.          * limit together with Precision.EPSILON to generate the following
  74.          * code (a priori, we know that there will be 16 elements, but it is
  75.          * better to not hardcode it).
  76.          */
  77.         final ResizableDoubleArray ra = new ResizableDoubleArray(20);

  78.         while (qi < 1) {
  79.             qi += FastMath.pow(LN2, i) / CombinatoricsUtils.factorial(i);
  80.             ra.addElement(qi);
  81.             ++i;
  82.         }

  83.         EXPONENTIAL_SA_QI = ra.getElements();
  84.     }

  85.     /**
  86.      * Create an exponential distribution with the given mean.
  87.      * <p>
  88.      * <b>Note:</b> this constructor will implicitly create an instance of
  89.      * {@link Well19937c} as random generator to be used for sampling only (see
  90.      * {@link #sample()} and {@link #sample(int)}). In case no sampling is
  91.      * needed for the created distribution, it is advised to pass {@code null}
  92.      * as random generator via the appropriate constructors to avoid the
  93.      * additional initialisation overhead.
  94.      *
  95.      * @param mean mean of this distribution.
  96.      */
  97.     public ExponentialDistribution(double mean) {
  98.         this(mean, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
  99.     }

  100.     /**
  101.      * Create an exponential distribution with the given mean.
  102.      * <p>
  103.      * <b>Note:</b> this constructor will implicitly create an instance of
  104.      * {@link Well19937c} as random generator to be used for sampling only (see
  105.      * {@link #sample()} and {@link #sample(int)}). In case no sampling is
  106.      * needed for the created distribution, it is advised to pass {@code null}
  107.      * as random generator via the appropriate constructors to avoid the
  108.      * additional initialisation overhead.
  109.      *
  110.      * @param mean Mean of this distribution.
  111.      * @param inverseCumAccuracy Maximum absolute error in inverse
  112.      * cumulative probability estimates (defaults to
  113.      * {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
  114.      * @throws NotStrictlyPositiveException if {@code mean <= 0}.
  115.      * @since 2.1
  116.      */
  117.     public ExponentialDistribution(double mean, double inverseCumAccuracy) {
  118.         this(new Well19937c(), mean, inverseCumAccuracy);
  119.     }

  120.     /**
  121.      * Creates an exponential distribution.
  122.      *
  123.      * @param rng Random number generator.
  124.      * @param mean Mean of this distribution.
  125.      * @throws NotStrictlyPositiveException if {@code mean <= 0}.
  126.      * @since 3.3
  127.      */
  128.     public ExponentialDistribution(RandomGenerator rng, double mean)
  129.         throws NotStrictlyPositiveException {
  130.         this(rng, mean, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
  131.     }

  132.     /**
  133.      * Creates an exponential distribution.
  134.      *
  135.      * @param rng Random number generator.
  136.      * @param mean Mean of this distribution.
  137.      * @param inverseCumAccuracy Maximum absolute error in inverse
  138.      * cumulative probability estimates (defaults to
  139.      * {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
  140.      * @throws NotStrictlyPositiveException if {@code mean <= 0}.
  141.      * @since 3.1
  142.      */
  143.     public ExponentialDistribution(RandomGenerator rng,
  144.                                    double mean,
  145.                                    double inverseCumAccuracy)
  146.         throws NotStrictlyPositiveException {
  147.         super(rng);

  148.         if (mean <= 0) {
  149.             throw new NotStrictlyPositiveException(LocalizedFormats.MEAN, mean);
  150.         }
  151.         this.mean = mean;
  152.         logMean = FastMath.log(mean);
  153.         solverAbsoluteAccuracy = inverseCumAccuracy;
  154.     }

  155.     /**
  156.      * Access the mean.
  157.      *
  158.      * @return the mean.
  159.      */
  160.     public double getMean() {
  161.         return mean;
  162.     }

  163.     /** {@inheritDoc} */
  164.     public double density(double x) {
  165.         final double logDensity = logDensity(x);
  166.         return logDensity == Double.NEGATIVE_INFINITY ? 0 : FastMath.exp(logDensity);
  167.     }

  168.     /** {@inheritDoc} **/
  169.     @Override
  170.     public double logDensity(double x) {
  171.         if (x < 0) {
  172.             return Double.NEGATIVE_INFINITY;
  173.         }
  174.         return -x / mean - logMean;
  175.     }

  176.     /**
  177.      * {@inheritDoc}
  178.      *
  179.      * The implementation of this method is based on:
  180.      * <ul>
  181.      * <li>
  182.      * <a href="http://mathworld.wolfram.com/ExponentialDistribution.html">
  183.      * Exponential Distribution</a>, equation (1).</li>
  184.      * </ul>
  185.      */
  186.     public double cumulativeProbability(double x)  {
  187.         double ret;
  188.         if (x <= 0.0) {
  189.             ret = 0.0;
  190.         } else {
  191.             ret = 1.0 - FastMath.exp(-x / mean);
  192.         }
  193.         return ret;
  194.     }

  195.     /**
  196.      * {@inheritDoc}
  197.      *
  198.      * Returns {@code 0} when {@code p= = 0} and
  199.      * {@code Double.POSITIVE_INFINITY} when {@code p == 1}.
  200.      */
  201.     @Override
  202.     public double inverseCumulativeProbability(double p) throws OutOfRangeException {
  203.         double ret;

  204.         if (p < 0.0 || p > 1.0) {
  205.             throw new OutOfRangeException(p, 0.0, 1.0);
  206.         } else if (p == 1.0) {
  207.             ret = Double.POSITIVE_INFINITY;
  208.         } else {
  209.             ret = -mean * FastMath.log(1.0 - p);
  210.         }

  211.         return ret;
  212.     }

  213.     /**
  214.      * {@inheritDoc}
  215.      *
  216.      * <p><strong>Algorithm Description</strong>: this implementation uses the
  217.      * <a href="http://www.jesus.ox.ac.uk/~clifford/a5/chap1/node5.html">
  218.      * Inversion Method</a> to generate exponentially distributed random values
  219.      * from uniform deviates.</p>
  220.      *
  221.      * @return a random value.
  222.      * @since 2.2
  223.      */
  224.     @Override
  225.     public double sample() {
  226.         // Step 1:
  227.         double a = 0;
  228.         double u = random.nextDouble();

  229.         // Step 2 and 3:
  230.         while (u < 0.5) {
  231.             a += EXPONENTIAL_SA_QI[0];
  232.             u *= 2;
  233.         }

  234.         // Step 4 (now u >= 0.5):
  235.         u += u - 1;

  236.         // Step 5:
  237.         if (u <= EXPONENTIAL_SA_QI[0]) {
  238.             return mean * (a + u);
  239.         }

  240.         // Step 6:
  241.         int i = 0; // Should be 1, be we iterate before it in while using 0
  242.         double u2 = random.nextDouble();
  243.         double umin = u2;

  244.         // Step 7 and 8:
  245.         do {
  246.             ++i;
  247.             u2 = random.nextDouble();

  248.             if (u2 < umin) {
  249.                 umin = u2;
  250.             }

  251.             // Step 8:
  252.         } while (u > EXPONENTIAL_SA_QI[i]); // Ensured to exit since EXPONENTIAL_SA_QI[MAX] = 1

  253.         return mean * (a + umin * EXPONENTIAL_SA_QI[0]);
  254.     }

  255.     /** {@inheritDoc} */
  256.     @Override
  257.     protected double getSolverAbsoluteAccuracy() {
  258.         return solverAbsoluteAccuracy;
  259.     }

  260.     /**
  261.      * {@inheritDoc}
  262.      *
  263.      * For mean parameter {@code k}, the mean is {@code k}.
  264.      */
  265.     public double getNumericalMean() {
  266.         return getMean();
  267.     }

  268.     /**
  269.      * {@inheritDoc}
  270.      *
  271.      * For mean parameter {@code k}, the variance is {@code k^2}.
  272.      */
  273.     public double getNumericalVariance() {
  274.         final double m = getMean();
  275.         return m * m;
  276.     }

  277.     /**
  278.      * {@inheritDoc}
  279.      *
  280.      * The lower bound of the support is always 0 no matter the mean parameter.
  281.      *
  282.      * @return lower bound of the support (always 0)
  283.      */
  284.     public double getSupportLowerBound() {
  285.         return 0;
  286.     }

  287.     /**
  288.      * {@inheritDoc}
  289.      *
  290.      * The upper bound of the support is always positive infinity
  291.      * no matter the mean parameter.
  292.      *
  293.      * @return upper bound of the support (always Double.POSITIVE_INFINITY)
  294.      */
  295.     public double getSupportUpperBound() {
  296.         return Double.POSITIVE_INFINITY;
  297.     }

  298.     /** {@inheritDoc} */
  299.     public boolean isSupportLowerBoundInclusive() {
  300.         return true;
  301.     }

  302.     /** {@inheritDoc} */
  303.     public boolean isSupportUpperBoundInclusive() {
  304.         return false;
  305.     }

  306.     /**
  307.      * {@inheritDoc}
  308.      *
  309.      * The support of this distribution is connected.
  310.      *
  311.      * @return {@code true}
  312.      */
  313.     public boolean isSupportConnected() {
  314.         return true;
  315.     }
  316. }