LogNormalDistribution.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.NumberIsTooLargeException;
  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.special.Erf;
  24. import org.apache.commons.math3.util.FastMath;

  25. /**
  26.  * Implementation of the log-normal (gaussian) distribution.
  27.  *
  28.  * <p>
  29.  * <strong>Parameters:</strong>
  30.  * {@code X} is log-normally distributed if its natural logarithm {@code log(X)}
  31.  * is normally distributed. The probability distribution function of {@code X}
  32.  * is given by (for {@code x > 0})
  33.  * </p>
  34.  * <p>
  35.  * {@code exp(-0.5 * ((ln(x) - m) / s)^2) / (s * sqrt(2 * pi) * x)}
  36.  * </p>
  37.  * <ul>
  38.  * <li>{@code m} is the <em>scale</em> parameter: this is the mean of the
  39.  * normally distributed natural logarithm of this distribution,</li>
  40.  * <li>{@code s} is the <em>shape</em> parameter: this is the standard
  41.  * deviation of the normally distributed natural logarithm of this
  42.  * distribution.
  43.  * </ul>
  44.  *
  45.  * @see <a href="http://en.wikipedia.org/wiki/Log-normal_distribution">
  46.  * Log-normal distribution (Wikipedia)</a>
  47.  * @see <a href="http://mathworld.wolfram.com/LogNormalDistribution.html">
  48.  * Log Normal distribution (MathWorld)</a>
  49.  *
  50.  * @since 3.0
  51.  */
  52. public class LogNormalDistribution extends AbstractRealDistribution {
  53.     /** Default inverse cumulative probability accuracy. */
  54.     public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;

  55.     /** Serializable version identifier. */
  56.     private static final long serialVersionUID = 20120112;

  57.     /** &radic;(2 &pi;) */
  58.     private static final double SQRT2PI = FastMath.sqrt(2 * FastMath.PI);

  59.     /** &radic;(2) */
  60.     private static final double SQRT2 = FastMath.sqrt(2.0);

  61.     /** The scale parameter of this distribution. */
  62.     private final double scale;

  63.     /** The shape parameter of this distribution. */
  64.     private final double shape;
  65.     /** The value of {@code log(shape) + 0.5 * log(2*PI)} stored for faster computation. */
  66.     private final double logShapePlusHalfLog2Pi;

  67.     /** Inverse cumulative probability accuracy. */
  68.     private final double solverAbsoluteAccuracy;

  69.     /**
  70.      * Create a log-normal distribution, where the mean and standard deviation
  71.      * of the {@link NormalDistribution normally distributed} natural
  72.      * logarithm of the log-normal distribution are equal to zero and one
  73.      * respectively. In other words, the scale of the returned distribution is
  74.      * {@code 0}, while its shape is {@code 1}.
  75.      * <p>
  76.      * <b>Note:</b> this constructor will implicitly create an instance of
  77.      * {@link Well19937c} as random generator to be used for sampling only (see
  78.      * {@link #sample()} and {@link #sample(int)}). In case no sampling is
  79.      * needed for the created distribution, it is advised to pass {@code null}
  80.      * as random generator via the appropriate constructors to avoid the
  81.      * additional initialisation overhead.
  82.      */
  83.     public LogNormalDistribution() {
  84.         this(0, 1);
  85.     }

  86.     /**
  87.      * Create a log-normal distribution using the specified scale and shape.
  88.      * <p>
  89.      * <b>Note:</b> this constructor will implicitly create an instance of
  90.      * {@link Well19937c} as random generator to be used for sampling only (see
  91.      * {@link #sample()} and {@link #sample(int)}). In case no sampling is
  92.      * needed for the created distribution, it is advised to pass {@code null}
  93.      * as random generator via the appropriate constructors to avoid the
  94.      * additional initialisation overhead.
  95.      *
  96.      * @param scale the scale parameter of this distribution
  97.      * @param shape the shape parameter of this distribution
  98.      * @throws NotStrictlyPositiveException if {@code shape <= 0}.
  99.      */
  100.     public LogNormalDistribution(double scale, double shape)
  101.         throws NotStrictlyPositiveException {
  102.         this(scale, shape, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
  103.     }

  104.     /**
  105.      * Create a log-normal distribution using the specified scale, shape and
  106.      * inverse cumulative distribution accuracy.
  107.      * <p>
  108.      * <b>Note:</b> this constructor will implicitly create an instance of
  109.      * {@link Well19937c} as random generator to be used for sampling only (see
  110.      * {@link #sample()} and {@link #sample(int)}). In case no sampling is
  111.      * needed for the created distribution, it is advised to pass {@code null}
  112.      * as random generator via the appropriate constructors to avoid the
  113.      * additional initialisation overhead.
  114.      *
  115.      * @param scale the scale parameter of this distribution
  116.      * @param shape the shape parameter of this distribution
  117.      * @param inverseCumAccuracy Inverse cumulative probability accuracy.
  118.      * @throws NotStrictlyPositiveException if {@code shape <= 0}.
  119.      */
  120.     public LogNormalDistribution(double scale, double shape, double inverseCumAccuracy)
  121.         throws NotStrictlyPositiveException {
  122.         this(new Well19937c(), scale, shape, inverseCumAccuracy);
  123.     }

  124.     /**
  125.      * Creates a log-normal distribution.
  126.      *
  127.      * @param rng Random number generator.
  128.      * @param scale Scale parameter of this distribution.
  129.      * @param shape Shape parameter of this distribution.
  130.      * @throws NotStrictlyPositiveException if {@code shape <= 0}.
  131.      * @since 3.3
  132.      */
  133.     public LogNormalDistribution(RandomGenerator rng, double scale, double shape)
  134.         throws NotStrictlyPositiveException {
  135.         this(rng, scale, shape, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
  136.     }

  137.     /**
  138.      * Creates a log-normal distribution.
  139.      *
  140.      * @param rng Random number generator.
  141.      * @param scale Scale parameter of this distribution.
  142.      * @param shape Shape parameter of this distribution.
  143.      * @param inverseCumAccuracy Inverse cumulative probability accuracy.
  144.      * @throws NotStrictlyPositiveException if {@code shape <= 0}.
  145.      * @since 3.1
  146.      */
  147.     public LogNormalDistribution(RandomGenerator rng,
  148.                                  double scale,
  149.                                  double shape,
  150.                                  double inverseCumAccuracy)
  151.         throws NotStrictlyPositiveException {
  152.         super(rng);

  153.         if (shape <= 0) {
  154.             throw new NotStrictlyPositiveException(LocalizedFormats.SHAPE, shape);
  155.         }

  156.         this.scale = scale;
  157.         this.shape = shape;
  158.         this.logShapePlusHalfLog2Pi = FastMath.log(shape) + 0.5 * FastMath.log(2 * FastMath.PI);
  159.         this.solverAbsoluteAccuracy = inverseCumAccuracy;
  160.     }

  161.     /**
  162.      * Returns the scale parameter of this distribution.
  163.      *
  164.      * @return the scale parameter
  165.      */
  166.     public double getScale() {
  167.         return scale;
  168.     }

  169.     /**
  170.      * Returns the shape parameter of this distribution.
  171.      *
  172.      * @return the shape parameter
  173.      */
  174.     public double getShape() {
  175.         return shape;
  176.     }

  177.     /**
  178.      * {@inheritDoc}
  179.      *
  180.      * For scale {@code m}, and shape {@code s} of this distribution, the PDF
  181.      * is given by
  182.      * <ul>
  183.      * <li>{@code 0} if {@code x <= 0},</li>
  184.      * <li>{@code exp(-0.5 * ((ln(x) - m) / s)^2) / (s * sqrt(2 * pi) * x)}
  185.      * otherwise.</li>
  186.      * </ul>
  187.      */
  188.     public double density(double x) {
  189.         if (x <= 0) {
  190.             return 0;
  191.         }
  192.         final double x0 = FastMath.log(x) - scale;
  193.         final double x1 = x0 / shape;
  194.         return FastMath.exp(-0.5 * x1 * x1) / (shape * SQRT2PI * x);
  195.     }

  196.     /** {@inheritDoc}
  197.      *
  198.      * See documentation of {@link #density(double)} for computation details.
  199.      */
  200.     @Override
  201.     public double logDensity(double x) {
  202.         if (x <= 0) {
  203.             return Double.NEGATIVE_INFINITY;
  204.         }
  205.         final double logX = FastMath.log(x);
  206.         final double x0 = logX - scale;
  207.         final double x1 = x0 / shape;
  208.         return -0.5 * x1 * x1 - (logShapePlusHalfLog2Pi + logX);
  209.     }

  210.     /**
  211.      * {@inheritDoc}
  212.      *
  213.      * For scale {@code m}, and shape {@code s} of this distribution, the CDF
  214.      * is given by
  215.      * <ul>
  216.      * <li>{@code 0} if {@code x <= 0},</li>
  217.      * <li>{@code 0} if {@code ln(x) - m < 0} and {@code m - ln(x) > 40 * s}, as
  218.      * in these cases the actual value is within {@code Double.MIN_VALUE} of 0,
  219.      * <li>{@code 1} if {@code ln(x) - m >= 0} and {@code ln(x) - m > 40 * s},
  220.      * as in these cases the actual value is within {@code Double.MIN_VALUE} of
  221.      * 1,</li>
  222.      * <li>{@code 0.5 + 0.5 * erf((ln(x) - m) / (s * sqrt(2))} otherwise.</li>
  223.      * </ul>
  224.      */
  225.     public double cumulativeProbability(double x)  {
  226.         if (x <= 0) {
  227.             return 0;
  228.         }
  229.         final double dev = FastMath.log(x) - scale;
  230.         if (FastMath.abs(dev) > 40 * shape) {
  231.             return dev < 0 ? 0.0d : 1.0d;
  232.         }
  233.         return 0.5 + 0.5 * Erf.erf(dev / (shape * SQRT2));
  234.     }

  235.     /**
  236.      * {@inheritDoc}
  237.      *
  238.      * @deprecated See {@link RealDistribution#cumulativeProbability(double,double)}
  239.      */
  240.     @Override@Deprecated
  241.     public double cumulativeProbability(double x0, double x1)
  242.         throws NumberIsTooLargeException {
  243.         return probability(x0, x1);
  244.     }

  245.     /** {@inheritDoc} */
  246.     @Override
  247.     public double probability(double x0,
  248.                               double x1)
  249.         throws NumberIsTooLargeException {
  250.         if (x0 > x1) {
  251.             throw new NumberIsTooLargeException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT,
  252.                                                 x0, x1, true);
  253.         }
  254.         if (x0 <= 0 || x1 <= 0) {
  255.             return super.probability(x0, x1);
  256.         }
  257.         final double denom = shape * SQRT2;
  258.         final double v0 = (FastMath.log(x0) - scale) / denom;
  259.         final double v1 = (FastMath.log(x1) - scale) / denom;
  260.         return 0.5 * Erf.erf(v0, v1);
  261.     }

  262.     /** {@inheritDoc} */
  263.     @Override
  264.     protected double getSolverAbsoluteAccuracy() {
  265.         return solverAbsoluteAccuracy;
  266.     }

  267.     /**
  268.      * {@inheritDoc}
  269.      *
  270.      * For scale {@code m} and shape {@code s}, the mean is
  271.      * {@code exp(m + s^2 / 2)}.
  272.      */
  273.     public double getNumericalMean() {
  274.         double s = shape;
  275.         return FastMath.exp(scale + (s * s / 2));
  276.     }

  277.     /**
  278.      * {@inheritDoc}
  279.      *
  280.      * For scale {@code m} and shape {@code s}, the variance is
  281.      * {@code (exp(s^2) - 1) * exp(2 * m + s^2)}.
  282.      */
  283.     public double getNumericalVariance() {
  284.         final double s = shape;
  285.         final double ss = s * s;
  286.         return (FastMath.expm1(ss)) * FastMath.exp(2 * scale + ss);
  287.     }

  288.     /**
  289.      * {@inheritDoc}
  290.      *
  291.      * The lower bound of the support is always 0 no matter the parameters.
  292.      *
  293.      * @return lower bound of the support (always 0)
  294.      */
  295.     public double getSupportLowerBound() {
  296.         return 0;
  297.     }

  298.     /**
  299.      * {@inheritDoc}
  300.      *
  301.      * The upper bound of the support is always positive infinity
  302.      * no matter the parameters.
  303.      *
  304.      * @return upper bound of the support (always
  305.      * {@code Double.POSITIVE_INFINITY})
  306.      */
  307.     public double getSupportUpperBound() {
  308.         return Double.POSITIVE_INFINITY;
  309.     }

  310.     /** {@inheritDoc} */
  311.     public boolean isSupportLowerBoundInclusive() {
  312.         return true;
  313.     }

  314.     /** {@inheritDoc} */
  315.     public boolean isSupportUpperBoundInclusive() {
  316.         return false;
  317.     }

  318.     /**
  319.      * {@inheritDoc}
  320.      *
  321.      * The support of this distribution is connected.
  322.      *
  323.      * @return {@code true}
  324.      */
  325.     public boolean isSupportConnected() {
  326.         return true;
  327.     }

  328.     /** {@inheritDoc} */
  329.     @Override
  330.     public double sample()  {
  331.         final double n = random.nextGaussian();
  332.         return FastMath.exp(scale + shape * n);
  333.     }
  334. }