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 * @since 3.0
054 */
055public class LogNormalDistribution extends AbstractRealDistribution {
056    /** Default inverse cumulative probability accuracy. */
057    public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
058
059    /** Serializable version identifier. */
060    private static final long serialVersionUID = 20120112;
061
062    /** &radic;(2 &pi;) */
063    private static final double SQRT2PI = FastMath.sqrt(2 * FastMath.PI);
064
065    /** &radic;(2) */
066    private static final double SQRT2 = FastMath.sqrt(2.0);
067
068    /** The scale parameter of this distribution. */
069    private final double scale;
070
071    /** The shape parameter of this distribution. */
072    private final double shape;
073    /** The value of {@code log(shape) + 0.5 * log(2*PI)} stored for faster computation. */
074    private final double logShapePlusHalfLog2Pi;
075
076    /** Inverse cumulative probability accuracy. */
077    private final double solverAbsoluteAccuracy;
078
079    /**
080     * Create a log-normal distribution, where the mean and standard deviation
081     * of the {@link NormalDistribution normally distributed} natural
082     * logarithm of the log-normal distribution are equal to zero and one
083     * respectively. In other words, the scale of the returned distribution is
084     * {@code 0}, while its shape is {@code 1}.
085     */
086    public LogNormalDistribution() {
087        this(0, 1);
088    }
089
090    /**
091     * Create a log-normal distribution using the specified scale and shape.
092     *
093     * @param scale the scale parameter of this distribution
094     * @param shape the shape parameter of this distribution
095     * @throws NotStrictlyPositiveException if {@code shape <= 0}.
096     */
097    public LogNormalDistribution(double scale, double shape)
098        throws NotStrictlyPositiveException {
099        this(scale, shape, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
100    }
101
102    /**
103     * Create a log-normal distribution using the specified scale, shape and
104     * inverse cumulative distribution accuracy.
105     *
106     * @param scale the scale parameter of this distribution
107     * @param shape the shape parameter of this distribution
108     * @param inverseCumAccuracy Inverse cumulative probability accuracy.
109     * @throws NotStrictlyPositiveException if {@code shape <= 0}.
110     */
111    public LogNormalDistribution(double scale, double shape, double inverseCumAccuracy)
112        throws NotStrictlyPositiveException {
113        this(new Well19937c(), scale, shape, inverseCumAccuracy);
114    }
115
116    /**
117     * Creates a log-normal distribution.
118     *
119     * @param rng Random number generator.
120     * @param scale Scale parameter of this distribution.
121     * @param shape Shape parameter of this distribution.
122     * @throws NotStrictlyPositiveException if {@code shape <= 0}.
123     * @since 3.3
124     */
125    public LogNormalDistribution(RandomGenerator rng, double scale, double shape)
126        throws NotStrictlyPositiveException {
127        this(rng, scale, shape, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
128    }
129
130    /**
131     * Creates a log-normal distribution.
132     *
133     * @param rng Random number generator.
134     * @param scale Scale parameter of this distribution.
135     * @param shape Shape parameter of this distribution.
136     * @param inverseCumAccuracy Inverse cumulative probability accuracy.
137     * @throws NotStrictlyPositiveException if {@code shape <= 0}.
138     * @since 3.1
139     */
140    public LogNormalDistribution(RandomGenerator rng,
141                                 double scale,
142                                 double shape,
143                                 double inverseCumAccuracy)
144        throws NotStrictlyPositiveException {
145        super(rng);
146
147        if (shape <= 0) {
148            throw new NotStrictlyPositiveException(LocalizedFormats.SHAPE, shape);
149        }
150
151        this.scale = scale;
152        this.shape = shape;
153        this.logShapePlusHalfLog2Pi = FastMath.log(shape) + 0.5 * FastMath.log(2 * FastMath.PI);
154        this.solverAbsoluteAccuracy = inverseCumAccuracy;
155    }
156
157    /**
158     * Returns the scale parameter of this distribution.
159     *
160     * @return the scale parameter
161     */
162    public double getScale() {
163        return scale;
164    }
165
166    /**
167     * Returns the shape parameter of this distribution.
168     *
169     * @return the shape parameter
170     */
171    public double getShape() {
172        return shape;
173    }
174
175    /**
176     * {@inheritDoc}
177     *
178     * For scale {@code m}, and shape {@code s} of this distribution, the PDF
179     * is given by
180     * <ul>
181     * <li>{@code 0} if {@code x <= 0},</li>
182     * <li>{@code exp(-0.5 * ((ln(x) - m) / s)^2) / (s * sqrt(2 * pi) * x)}
183     * otherwise.</li>
184     * </ul>
185     */
186    public double density(double x) {
187        if (x <= 0) {
188            return 0;
189        }
190        final double x0 = FastMath.log(x) - scale;
191        final double x1 = x0 / shape;
192        return FastMath.exp(-0.5 * x1 * x1) / (shape * SQRT2PI * x);
193    }
194
195    /** {@inheritDoc}
196     *
197     * See documentation of {@link #density(double)} for computation details.
198     */
199    @Override
200    public double logDensity(double x) {
201        if (x <= 0) {
202            return Double.NEGATIVE_INFINITY;
203        }
204        final double logX = FastMath.log(x);
205        final double x0 = logX - scale;
206        final double x1 = x0 / shape;
207        return -0.5 * x1 * x1 - (logShapePlusHalfLog2Pi + logX);
208    }
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    /**
237     * {@inheritDoc}
238     *
239     * @deprecated See {@link RealDistribution#cumulativeProbability(double,double)}
240     */
241    @Override@Deprecated
242    public double cumulativeProbability(double x0, double x1)
243        throws NumberIsTooLargeException {
244        return probability(x0, x1);
245    }
246
247    /** {@inheritDoc} */
248    @Override
249    public double probability(double x0,
250                              double x1)
251        throws NumberIsTooLargeException {
252        if (x0 > x1) {
253            throw new NumberIsTooLargeException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT,
254                                                x0, x1, true);
255        }
256        if (x0 <= 0 || x1 <= 0) {
257            return super.probability(x0, x1);
258        }
259        final double denom = shape * SQRT2;
260        final double v0 = (FastMath.log(x0) - scale) / denom;
261        final double v1 = (FastMath.log(x1) - scale) / denom;
262        return 0.5 * Erf.erf(v0, v1);
263    }
264
265    /** {@inheritDoc} */
266    @Override
267    protected double getSolverAbsoluteAccuracy() {
268        return solverAbsoluteAccuracy;
269    }
270
271    /**
272     * {@inheritDoc}
273     *
274     * For scale {@code m} and shape {@code s}, the mean is
275     * {@code exp(m + s^2 / 2)}.
276     */
277    public double getNumericalMean() {
278        double s = shape;
279        return FastMath.exp(scale + (s * s / 2));
280    }
281
282    /**
283     * {@inheritDoc}
284     *
285     * For scale {@code m} and shape {@code s}, the variance is
286     * {@code (exp(s^2) - 1) * exp(2 * m + s^2)}.
287     */
288    public double getNumericalVariance() {
289        final double s = shape;
290        final double ss = s * s;
291        return (FastMath.expm1(ss)) * FastMath.exp(2 * scale + ss);
292    }
293
294    /**
295     * {@inheritDoc}
296     *
297     * The lower bound of the support is always 0 no matter the parameters.
298     *
299     * @return lower bound of the support (always 0)
300     */
301    public double getSupportLowerBound() {
302        return 0;
303    }
304
305    /**
306     * {@inheritDoc}
307     *
308     * The upper bound of the support is always positive infinity
309     * no matter the parameters.
310     *
311     * @return upper bound of the support (always
312     * {@code Double.POSITIVE_INFINITY})
313     */
314    public double getSupportUpperBound() {
315        return Double.POSITIVE_INFINITY;
316    }
317
318    /** {@inheritDoc} */
319    public boolean isSupportLowerBoundInclusive() {
320        return true;
321    }
322
323    /** {@inheritDoc} */
324    public boolean isSupportUpperBoundInclusive() {
325        return false;
326    }
327
328    /**
329     * {@inheritDoc}
330     *
331     * The support of this distribution is connected.
332     *
333     * @return {@code true}
334     */
335    public boolean isSupportConnected() {
336        return true;
337    }
338
339    /** {@inheritDoc} */
340    @Override
341    public double sample()  {
342        final double n = random.nextGaussian();
343        return FastMath.exp(scale + shape * n);
344    }
345}