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.NumberIsTooLargeException;
021import org.apache.commons.math3.exception.NumberIsTooSmallException;
022import org.apache.commons.math3.exception.OutOfRangeException;
023import org.apache.commons.math3.exception.util.LocalizedFormats;
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 triangular real distribution.
030 *
031 * @see <a href="http://en.wikipedia.org/wiki/Triangular_distribution">
032 * Triangular distribution (Wikipedia)</a>
033 *
034 * @since 3.0
035 */
036public class TriangularDistribution extends AbstractRealDistribution {
037    /** Serializable version identifier. */
038    private static final long serialVersionUID = 20120112L;
039    /** Lower limit of this distribution (inclusive). */
040    private final double a;
041    /** Upper limit of this distribution (inclusive). */
042    private final double b;
043    /** Mode of this distribution. */
044    private final double c;
045    /** Inverse cumulative probability accuracy. */
046    private final double solverAbsoluteAccuracy;
047
048    /**
049     * Creates a triangular real distribution using the given lower limit,
050     * upper limit, and mode.
051     *
052     * @param a Lower limit of this distribution (inclusive).
053     * @param b Upper limit of this distribution (inclusive).
054     * @param c Mode of this distribution.
055     * @throws NumberIsTooLargeException if {@code a >= b} or if {@code c > b}.
056     * @throws NumberIsTooSmallException if {@code c < a}.
057     */
058    public TriangularDistribution(double a, double c, double b)
059        throws NumberIsTooLargeException, NumberIsTooSmallException {
060        this(new Well19937c(), a, c, b);
061    }
062
063    /**
064     * Creates a triangular distribution.
065     *
066     * @param rng Random number generator.
067     * @param a Lower limit of this distribution (inclusive).
068     * @param b Upper limit of this distribution (inclusive).
069     * @param c Mode of this distribution.
070     * @throws NumberIsTooLargeException if {@code a >= b} or if {@code c > b}.
071     * @throws NumberIsTooSmallException if {@code c < a}.
072     * @since 3.1
073     */
074    public TriangularDistribution(RandomGenerator rng,
075                                  double a,
076                                  double c,
077                                  double b)
078        throws NumberIsTooLargeException, NumberIsTooSmallException {
079        super(rng);
080
081        if (a >= b) {
082            throw new NumberIsTooLargeException(
083                            LocalizedFormats.LOWER_BOUND_NOT_BELOW_UPPER_BOUND,
084                            a, b, false);
085        }
086        if (c < a) {
087            throw new NumberIsTooSmallException(
088                    LocalizedFormats.NUMBER_TOO_SMALL, c, a, true);
089        }
090        if (c > b) {
091            throw new NumberIsTooLargeException(
092                    LocalizedFormats.NUMBER_TOO_LARGE, c, b, true);
093        }
094
095        this.a = a;
096        this.c = c;
097        this.b = b;
098        solverAbsoluteAccuracy = FastMath.max(FastMath.ulp(a), FastMath.ulp(b));
099    }
100
101    /**
102     * Returns the mode {@code c} of this distribution.
103     *
104     * @return the mode {@code c} of this distribution
105     */
106    public double getMode() {
107        return c;
108    }
109
110    /**
111     * {@inheritDoc}
112     *
113     * <p>
114     * For this distribution, the returned value is not really meaningful,
115     * since exact formulas are implemented for the computation of the
116     * {@link #inverseCumulativeProbability(double)} (no solver is invoked).
117     * </p>
118     * <p>
119     * For lower limit {@code a} and upper limit {@code b}, the current
120     * implementation returns {@code max(ulp(a), ulp(b)}.
121     * </p>
122     */
123    @Override
124    protected double getSolverAbsoluteAccuracy() {
125        return solverAbsoluteAccuracy;
126    }
127
128    /**
129     * {@inheritDoc}
130     *
131     * For lower limit {@code a}, upper limit {@code b} and mode {@code c}, the
132     * PDF is given by
133     * <ul>
134     * <li>{@code 2 * (x - a) / [(b - a) * (c - a)]} if {@code a <= x < c},</li>
135     * <li>{@code 2 / (b - a)} if {@code x = c},</li>
136     * <li>{@code 2 * (b - x) / [(b - a) * (b - c)]} if {@code c < x <= b},</li>
137     * <li>{@code 0} otherwise.
138     * </ul>
139     */
140    public double density(double x) {
141        if (x < a) {
142            return 0;
143        }
144        if (a <= x && x < c) {
145            double divident = 2 * (x - a);
146            double divisor = (b - a) * (c - a);
147            return divident / divisor;
148        }
149        if (x == c) {
150            return 2 / (b - a);
151        }
152        if (c < x && x <= b) {
153            double divident = 2 * (b - x);
154            double divisor = (b - a) * (b - c);
155            return divident / divisor;
156        }
157        return 0;
158    }
159
160    /**
161     * {@inheritDoc}
162     *
163     * For lower limit {@code a}, upper limit {@code b} and mode {@code c}, the
164     * CDF is given by
165     * <ul>
166     * <li>{@code 0} if {@code x < a},</li>
167     * <li>{@code (x - a)^2 / [(b - a) * (c - a)]} if {@code a <= x < c},</li>
168     * <li>{@code (c - a) / (b - a)} if {@code x = c},</li>
169     * <li>{@code 1 - (b - x)^2 / [(b - a) * (b - c)]} if {@code c < x <= b},</li>
170     * <li>{@code 1} if {@code x > b}.</li>
171     * </ul>
172     */
173    public double cumulativeProbability(double x)  {
174        if (x < a) {
175            return 0;
176        }
177        if (a <= x && x < c) {
178            double divident = (x - a) * (x - a);
179            double divisor = (b - a) * (c - a);
180            return divident / divisor;
181        }
182        if (x == c) {
183            return (c - a) / (b - a);
184        }
185        if (c < x && x <= b) {
186            double divident = (b - x) * (b - x);
187            double divisor = (b - a) * (b - c);
188            return 1 - (divident / divisor);
189        }
190        return 1;
191    }
192
193    /**
194     * {@inheritDoc}
195     *
196     * For lower limit {@code a}, upper limit {@code b}, and mode {@code c},
197     * the mean is {@code (a + b + c) / 3}.
198     */
199    public double getNumericalMean() {
200        return (a + b + c) / 3;
201    }
202
203    /**
204     * {@inheritDoc}
205     *
206     * For lower limit {@code a}, upper limit {@code b}, and mode {@code c},
207     * the variance is {@code (a^2 + b^2 + c^2 - a * b - a * c - b * c) / 18}.
208     */
209    public double getNumericalVariance() {
210        return (a * a + b * b + c * c - a * b - a * c - b * c) / 18;
211    }
212
213    /**
214     * {@inheritDoc}
215     *
216     * The lower bound of the support is equal to the lower limit parameter
217     * {@code a} of the distribution.
218     *
219     * @return lower bound of the support
220     */
221    public double getSupportLowerBound() {
222        return a;
223    }
224
225    /**
226     * {@inheritDoc}
227     *
228     * The upper bound of the support is equal to the upper limit parameter
229     * {@code b} of the distribution.
230     *
231     * @return upper bound of the support
232     */
233    public double getSupportUpperBound() {
234        return b;
235    }
236
237    /** {@inheritDoc} */
238    public boolean isSupportLowerBoundInclusive() {
239        return true;
240    }
241
242    /** {@inheritDoc} */
243    public boolean isSupportUpperBoundInclusive() {
244        return true;
245    }
246
247    /**
248     * {@inheritDoc}
249     *
250     * The support of this distribution is connected.
251     *
252     * @return {@code true}
253     */
254    public boolean isSupportConnected() {
255        return true;
256    }
257
258    @Override
259    public double inverseCumulativeProbability(double p)
260        throws OutOfRangeException {
261        if (p < 0 || p > 1) {
262            throw new OutOfRangeException(p, 0, 1);
263        }
264        if (p == 0) {
265            return a;
266        }
267        if (p == 1) {
268            return b;
269        }
270        if (p < (c - a) / (b - a)) {
271            return a + FastMath.sqrt(p * (b - a) * (c - a));
272        }
273        return b - FastMath.sqrt((1 - p) * (b - a) * (b - c));
274    }
275}