TDistribution.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.util.LocalizedFormats;
  20. import org.apache.commons.math3.random.RandomGenerator;
  21. import org.apache.commons.math3.random.Well19937c;
  22. import org.apache.commons.math3.special.Beta;
  23. import org.apache.commons.math3.special.Gamma;
  24. import org.apache.commons.math3.util.FastMath;

  25. /**
  26.  * Implementation of Student's t-distribution.
  27.  *
  28.  * @see "<a href='http://en.wikipedia.org/wiki/Student&apos;s_t-distribution'>Student's t-distribution (Wikipedia)</a>"
  29.  * @see "<a href='http://mathworld.wolfram.com/Studentst-Distribution.html'>Student's t-distribution (MathWorld)</a>"
  30.  */
  31. public class TDistribution extends AbstractRealDistribution {
  32.     /**
  33.      * Default inverse cumulative probability accuracy.
  34.      * @since 2.1
  35.      */
  36.     public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
  37.     /** Serializable version identifier */
  38.     private static final long serialVersionUID = -5852615386664158222L;
  39.     /** The degrees of freedom. */
  40.     private final double degreesOfFreedom;
  41.     /** Inverse cumulative probability accuracy. */
  42.     private final double solverAbsoluteAccuracy;
  43.     /** Static computation factor based on degreesOfFreedom. */
  44.     private final double factor;

  45.     /**
  46.      * Create a t distribution using the given degrees of freedom.
  47.      * <p>
  48.      * <b>Note:</b> this constructor will implicitly create an instance of
  49.      * {@link Well19937c} as random generator to be used for sampling only (see
  50.      * {@link #sample()} and {@link #sample(int)}). In case no sampling is
  51.      * needed for the created distribution, it is advised to pass {@code null}
  52.      * as random generator via the appropriate constructors to avoid the
  53.      * additional initialisation overhead.
  54.      *
  55.      * @param degreesOfFreedom Degrees of freedom.
  56.      * @throws NotStrictlyPositiveException if {@code degreesOfFreedom <= 0}
  57.      */
  58.     public TDistribution(double degreesOfFreedom)
  59.         throws NotStrictlyPositiveException {
  60.         this(degreesOfFreedom, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
  61.     }

  62.     /**
  63.      * Create a t distribution using the given degrees of freedom and the
  64.      * specified inverse cumulative probability absolute accuracy.
  65.      * <p>
  66.      * <b>Note:</b> this constructor will implicitly create an instance of
  67.      * {@link Well19937c} as random generator to be used for sampling only (see
  68.      * {@link #sample()} and {@link #sample(int)}). In case no sampling is
  69.      * needed for the created distribution, it is advised to pass {@code null}
  70.      * as random generator via the appropriate constructors to avoid the
  71.      * additional initialisation overhead.
  72.      *
  73.      * @param degreesOfFreedom Degrees of freedom.
  74.      * @param inverseCumAccuracy the maximum absolute error in inverse
  75.      * cumulative probability estimates
  76.      * (defaults to {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
  77.      * @throws NotStrictlyPositiveException if {@code degreesOfFreedom <= 0}
  78.      * @since 2.1
  79.      */
  80.     public TDistribution(double degreesOfFreedom, double inverseCumAccuracy)
  81.         throws NotStrictlyPositiveException {
  82.         this(new Well19937c(), degreesOfFreedom, inverseCumAccuracy);
  83.     }

  84.     /**
  85.      * Creates a t distribution.
  86.      *
  87.      * @param rng Random number generator.
  88.      * @param degreesOfFreedom Degrees of freedom.
  89.      * @throws NotStrictlyPositiveException if {@code degreesOfFreedom <= 0}
  90.      * @since 3.3
  91.      */
  92.     public TDistribution(RandomGenerator rng, double degreesOfFreedom)
  93.         throws NotStrictlyPositiveException {
  94.         this(rng, degreesOfFreedom, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
  95.     }

  96.     /**
  97.      * Creates a t distribution.
  98.      *
  99.      * @param rng Random number generator.
  100.      * @param degreesOfFreedom Degrees of freedom.
  101.      * @param inverseCumAccuracy the maximum absolute error in inverse
  102.      * cumulative probability estimates
  103.      * (defaults to {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
  104.      * @throws NotStrictlyPositiveException if {@code degreesOfFreedom <= 0}
  105.      * @since 3.1
  106.      */
  107.     public TDistribution(RandomGenerator rng,
  108.                          double degreesOfFreedom,
  109.                          double inverseCumAccuracy)
  110.         throws NotStrictlyPositiveException {
  111.         super(rng);

  112.         if (degreesOfFreedom <= 0) {
  113.             throw new NotStrictlyPositiveException(LocalizedFormats.DEGREES_OF_FREEDOM,
  114.                                                    degreesOfFreedom);
  115.         }
  116.         this.degreesOfFreedom = degreesOfFreedom;
  117.         solverAbsoluteAccuracy = inverseCumAccuracy;

  118.         final double n = degreesOfFreedom;
  119.         final double nPlus1Over2 = (n + 1) / 2;
  120.         factor = Gamma.logGamma(nPlus1Over2) -
  121.                  0.5 * (FastMath.log(FastMath.PI) + FastMath.log(n)) -
  122.                  Gamma.logGamma(n / 2);
  123.     }

  124.     /**
  125.      * Access the degrees of freedom.
  126.      *
  127.      * @return the degrees of freedom.
  128.      */
  129.     public double getDegreesOfFreedom() {
  130.         return degreesOfFreedom;
  131.     }

  132.     /** {@inheritDoc} */
  133.     public double density(double x) {
  134.         return FastMath.exp(logDensity(x));
  135.     }

  136.     /** {@inheritDoc} */
  137.     @Override
  138.     public double logDensity(double x) {
  139.         final double n = degreesOfFreedom;
  140.         final double nPlus1Over2 = (n + 1) / 2;
  141.         return factor - nPlus1Over2 * FastMath.log(1 + x * x / n);
  142.     }

  143.     /** {@inheritDoc} */
  144.     public double cumulativeProbability(double x) {
  145.         double ret;
  146.         if (x == 0) {
  147.             ret = 0.5;
  148.         } else {
  149.             double t =
  150.                 Beta.regularizedBeta(
  151.                     degreesOfFreedom / (degreesOfFreedom + (x * x)),
  152.                     0.5 * degreesOfFreedom,
  153.                     0.5);
  154.             if (x < 0.0) {
  155.                 ret = 0.5 * t;
  156.             } else {
  157.                 ret = 1.0 - 0.5 * t;
  158.             }
  159.         }

  160.         return ret;
  161.     }

  162.     /** {@inheritDoc} */
  163.     @Override
  164.     protected double getSolverAbsoluteAccuracy() {
  165.         return solverAbsoluteAccuracy;
  166.     }

  167.     /**
  168.      * {@inheritDoc}
  169.      *
  170.      * For degrees of freedom parameter {@code df}, the mean is
  171.      * <ul>
  172.      *  <li>if {@code df > 1} then {@code 0},</li>
  173.      * <li>else undefined ({@code Double.NaN}).</li>
  174.      * </ul>
  175.      */
  176.     public double getNumericalMean() {
  177.         final double df = getDegreesOfFreedom();

  178.         if (df > 1) {
  179.             return 0;
  180.         }

  181.         return Double.NaN;
  182.     }

  183.     /**
  184.      * {@inheritDoc}
  185.      *
  186.      * For degrees of freedom parameter {@code df}, the variance is
  187.      * <ul>
  188.      *  <li>if {@code df > 2} then {@code df / (df - 2)},</li>
  189.      *  <li>if {@code 1 < df <= 2} then positive infinity
  190.      *  ({@code Double.POSITIVE_INFINITY}),</li>
  191.      *  <li>else undefined ({@code Double.NaN}).</li>
  192.      * </ul>
  193.      */
  194.     public double getNumericalVariance() {
  195.         final double df = getDegreesOfFreedom();

  196.         if (df > 2) {
  197.             return df / (df - 2);
  198.         }

  199.         if (df > 1 && df <= 2) {
  200.             return Double.POSITIVE_INFINITY;
  201.         }

  202.         return Double.NaN;
  203.     }

  204.     /**
  205.      * {@inheritDoc}
  206.      *
  207.      * The lower bound of the support is always negative infinity no matter the
  208.      * parameters.
  209.      *
  210.      * @return lower bound of the support (always
  211.      * {@code Double.NEGATIVE_INFINITY})
  212.      */
  213.     public double getSupportLowerBound() {
  214.         return Double.NEGATIVE_INFINITY;
  215.     }

  216.     /**
  217.      * {@inheritDoc}
  218.      *
  219.      * The upper bound of the support is always positive infinity no matter the
  220.      * parameters.
  221.      *
  222.      * @return upper bound of the support (always
  223.      * {@code Double.POSITIVE_INFINITY})
  224.      */
  225.     public double getSupportUpperBound() {
  226.         return Double.POSITIVE_INFINITY;
  227.     }

  228.     /** {@inheritDoc} */
  229.     public boolean isSupportLowerBoundInclusive() {
  230.         return false;
  231.     }

  232.     /** {@inheritDoc} */
  233.     public boolean isSupportUpperBoundInclusive() {
  234.         return false;
  235.     }

  236.     /**
  237.      * {@inheritDoc}
  238.      *
  239.      * The support of this distribution is connected.
  240.      *
  241.      * @return {@code true}
  242.      */
  243.     public boolean isSupportConnected() {
  244.         return true;
  245.     }
  246. }