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 */
017
018package org.apache.commons.math3.distribution;
019
020import org.apache.commons.math3.exception.NotStrictlyPositiveException;
021import org.apache.commons.math3.exception.NumberIsTooLargeException;
022import org.apache.commons.math3.exception.util.LocalizedFormats;
023import org.apache.commons.math3.special.Erf;
024import org.apache.commons.math3.util.FastMath;
025import org.apache.commons.math3.random.RandomGenerator;
026import org.apache.commons.math3.random.Well19937c;
027
028/**
029 * Implementation of the log-normal (gaussian) distribution.
030 *
031 * <p>
032 * <strong>Parameters:</strong>
033 * {@code X} is log-normally distributed if its natural logarithm {@code log(X)}
034 * is normally distributed. The probability distribution function of {@code X}
035 * is given by (for {@code x > 0})
036 * </p>
037 * <p>
038 * {@code exp(-0.5 * ((ln(x) - m) / s)^2) / (s * sqrt(2 * pi) * x)}
039 * </p>
040 * <ul>
041 * <li>{@code m} is the <em>scale</em> parameter: this is the mean of the
042 * normally distributed natural logarithm of this distribution,</li>
043 * <li>{@code s} is the <em>shape</em> parameter: this is the standard
044 * deviation of the normally distributed natural logarithm of this
045 * distribution.
046 * </ul>
047 *
048 * @see <a href="http://en.wikipedia.org/wiki/Log-normal_distribution">
049 * Log-normal distribution (Wikipedia)</a>
050 * @see <a href="http://mathworld.wolfram.com/LogNormalDistribution.html">
051 * Log Normal distribution (MathWorld)</a>
052 *
053 * @version $Id: LogNormalDistribution.java 1538998 2013-11-05 13:51:24Z erans $
054 * @since 3.0
055 */
056public class LogNormalDistribution extends AbstractRealDistribution {
057    /** Default inverse cumulative probability accuracy. */
058    public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
059
060    /** Serializable version identifier. */
061    private static final long serialVersionUID = 20120112;
062
063    /** &radic;(2 &pi;) */
064    private static final double SQRT2PI = FastMath.sqrt(2 * FastMath.PI);
065
066    /** &radic;(2) */
067    private static final double SQRT2 = FastMath.sqrt(2.0);
068
069    /** The scale parameter of this distribution. */
070    private final double scale;
071
072    /** The shape parameter of this distribution. */
073    private final double shape;
074    /** The value of {@code log(shape) + 0.5 * log(2*PI)} stored for faster computation. */
075    private final double logShapePlusHalfLog2Pi;
076
077    /** Inverse cumulative probability accuracy. */
078    private final double solverAbsoluteAccuracy;
079
080    /**
081     * Create a log-normal distribution, where the mean and standard deviation
082     * of the {@link NormalDistribution normally distributed} natural
083     * logarithm of the log-normal distribution are equal to zero and one
084     * respectively. In other words, the scale of the returned distribution is
085     * {@code 0}, while its shape is {@code 1}.
086     */
087    public LogNormalDistribution() {
088        this(0, 1);
089    }
090
091    /**
092     * Create a log-normal distribution using the specified scale and shape.
093     *
094     * @param scale the scale parameter of this distribution
095     * @param shape the shape parameter of this distribution
096     * @throws NotStrictlyPositiveException if {@code shape <= 0}.
097     */
098    public LogNormalDistribution(double scale, double shape)
099        throws NotStrictlyPositiveException {
100        this(scale, shape, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
101    }
102
103    /**
104     * Create a log-normal distribution using the specified scale, shape and
105     * inverse cumulative distribution accuracy.
106     *
107     * @param scale the scale parameter of this distribution
108     * @param shape the shape parameter of this distribution
109     * @param inverseCumAccuracy Inverse cumulative probability accuracy.
110     * @throws NotStrictlyPositiveException if {@code shape <= 0}.
111     */
112    public LogNormalDistribution(double scale, double shape, double inverseCumAccuracy)
113        throws NotStrictlyPositiveException {
114        this(new Well19937c(), scale, shape, inverseCumAccuracy);
115    }
116
117    /**
118     * Creates a log-normal distribution.
119     *
120     * @param rng Random number generator.
121     * @param scale Scale parameter of this distribution.
122     * @param shape Shape parameter of this distribution.
123     * @throws NotStrictlyPositiveException if {@code shape <= 0}.
124     * @since 3.3
125     */
126    public LogNormalDistribution(RandomGenerator rng, double scale, double shape)
127        throws NotStrictlyPositiveException {
128        this(rng, scale, shape, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
129    }
130
131    /**
132     * Creates a log-normal distribution.
133     *
134     * @param rng Random number generator.
135     * @param scale Scale parameter of this distribution.
136     * @param shape Shape parameter of this distribution.
137     * @param inverseCumAccuracy Inverse cumulative probability accuracy.
138     * @throws NotStrictlyPositiveException if {@code shape <= 0}.
139     * @since 3.1
140     */
141    public LogNormalDistribution(RandomGenerator rng,
142                                 double scale,
143                                 double shape,
144                                 double inverseCumAccuracy)
145        throws NotStrictlyPositiveException {
146        super(rng);
147
148        if (shape <= 0) {
149            throw new NotStrictlyPositiveException(LocalizedFormats.SHAPE, shape);
150        }
151
152        this.scale = scale;
153        this.shape = shape;
154        this.logShapePlusHalfLog2Pi = FastMath.log(shape) + 0.5 * FastMath.log(2 * FastMath.PI);
155        this.solverAbsoluteAccuracy = inverseCumAccuracy;
156    }
157
158    /**
159     * Returns the scale parameter of this distribution.
160     *
161     * @return the scale parameter
162     */
163    public double getScale() {
164        return scale;
165    }
166
167    /**
168     * Returns the shape parameter of this distribution.
169     *
170     * @return the shape parameter
171     */
172    public double getShape() {
173        return shape;
174    }
175
176    /**
177     * {@inheritDoc}
178     *
179     * For scale {@code m}, and shape {@code s} of this distribution, the PDF
180     * is given by
181     * <ul>
182     * <li>{@code 0} if {@code x <= 0},</li>
183     * <li>{@code exp(-0.5 * ((ln(x) - m) / s)^2) / (s * sqrt(2 * pi) * x)}
184     * otherwise.</li>
185     * </ul>
186     */
187    public double density(double x) {
188        if (x <= 0) {
189            return 0;
190        }
191        final double x0 = FastMath.log(x) - scale;
192        final double x1 = x0 / shape;
193        return FastMath.exp(-0.5 * x1 * x1) / (shape * SQRT2PI * x);
194    }
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    /**
212     * {@inheritDoc}
213     *
214     * For scale {@code m}, and shape {@code s} of this distribution, the CDF
215     * is given by
216     * <ul>
217     * <li>{@code 0} if {@code x <= 0},</li>
218     * <li>{@code 0} if {@code ln(x) - m < 0} and {@code m - ln(x) > 40 * s}, as
219     * in these cases the actual value is within {@code Double.MIN_VALUE} of 0,
220     * <li>{@code 1} if {@code ln(x) - m >= 0} and {@code ln(x) - m > 40 * s},
221     * as in these cases the actual value is within {@code Double.MIN_VALUE} of
222     * 1,</li>
223     * <li>{@code 0.5 + 0.5 * erf((ln(x) - m) / (s * sqrt(2))} otherwise.</li>
224     * </ul>
225     */
226    public double cumulativeProbability(double x)  {
227        if (x <= 0) {
228            return 0;
229        }
230        final double dev = FastMath.log(x) - scale;
231        if (FastMath.abs(dev) > 40 * shape) {
232            return dev < 0 ? 0.0d : 1.0d;
233        }
234        return 0.5 + 0.5 * Erf.erf(dev / (shape * SQRT2));
235    }
236
237    /**
238     * {@inheritDoc}
239     *
240     * @deprecated See {@link RealDistribution#cumulativeProbability(double,double)}
241     */
242    @Override@Deprecated
243    public double cumulativeProbability(double x0, double x1)
244        throws NumberIsTooLargeException {
245        return probability(x0, x1);
246    }
247
248    /** {@inheritDoc} */
249    @Override
250    public double probability(double x0,
251                              double x1)
252        throws NumberIsTooLargeException {
253        if (x0 > x1) {
254            throw new NumberIsTooLargeException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT,
255                                                x0, x1, true);
256        }
257        if (x0 <= 0 || x1 <= 0) {
258            return super.probability(x0, x1);
259        }
260        final double denom = shape * SQRT2;
261        final double v0 = (FastMath.log(x0) - scale) / denom;
262        final double v1 = (FastMath.log(x1) - scale) / denom;
263        return 0.5 * Erf.erf(v0, v1);
264    }
265
266    /** {@inheritDoc} */
267    @Override
268    protected double getSolverAbsoluteAccuracy() {
269        return solverAbsoluteAccuracy;
270    }
271
272    /**
273     * {@inheritDoc}
274     *
275     * For scale {@code m} and shape {@code s}, the mean is
276     * {@code exp(m + s^2 / 2)}.
277     */
278    public double getNumericalMean() {
279        double s = shape;
280        return FastMath.exp(scale + (s * s / 2));
281    }
282
283    /**
284     * {@inheritDoc}
285     *
286     * For scale {@code m} and shape {@code s}, the variance is
287     * {@code (exp(s^2) - 1) * exp(2 * m + s^2)}.
288     */
289    public double getNumericalVariance() {
290        final double s = shape;
291        final double ss = s * s;
292        return (FastMath.expm1(ss)) * FastMath.exp(2 * scale + ss);
293    }
294
295    /**
296     * {@inheritDoc}
297     *
298     * The lower bound of the support is always 0 no matter the parameters.
299     *
300     * @return lower bound of the support (always 0)
301     */
302    public double getSupportLowerBound() {
303        return 0;
304    }
305
306    /**
307     * {@inheritDoc}
308     *
309     * The upper bound of the support is always positive infinity
310     * no matter the parameters.
311     *
312     * @return upper bound of the support (always
313     * {@code Double.POSITIVE_INFINITY})
314     */
315    public double getSupportUpperBound() {
316        return Double.POSITIVE_INFINITY;
317    }
318
319    /** {@inheritDoc} */
320    public boolean isSupportLowerBoundInclusive() {
321        return true;
322    }
323
324    /** {@inheritDoc} */
325    public boolean isSupportUpperBoundInclusive() {
326        return false;
327    }
328
329    /**
330     * {@inheritDoc}
331     *
332     * The support of this distribution is connected.
333     *
334     * @return {@code true}
335     */
336    public boolean isSupportConnected() {
337        return true;
338    }
339
340    /** {@inheritDoc} */
341    @Override
342    public double sample()  {
343        final double n = random.nextGaussian();
344        return FastMath.exp(scale + shape * n);
345    }
346}