You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by tn...@apache.org on 2015/02/16 23:40:04 UTC
[34/82] [partial] [math] Update for next development iteration:
commons-math4
http://git-wip-us.apache.org/repos/asf/commons-math/blob/a7b4803f/src/main/java/org/apache/commons/math3/distribution/AbstractRealDistribution.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/math3/distribution/AbstractRealDistribution.java b/src/main/java/org/apache/commons/math3/distribution/AbstractRealDistribution.java
deleted file mode 100644
index e3b1fac..0000000
--- a/src/main/java/org/apache/commons/math3/distribution/AbstractRealDistribution.java
+++ /dev/null
@@ -1,307 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.math3.distribution;
-
-import java.io.Serializable;
-
-import org.apache.commons.math3.analysis.UnivariateFunction;
-import org.apache.commons.math3.analysis.solvers.UnivariateSolverUtils;
-import org.apache.commons.math3.exception.NotStrictlyPositiveException;
-import org.apache.commons.math3.exception.NumberIsTooLargeException;
-import org.apache.commons.math3.exception.OutOfRangeException;
-import org.apache.commons.math3.exception.util.LocalizedFormats;
-import org.apache.commons.math3.random.RandomGenerator;
-import org.apache.commons.math3.random.RandomDataImpl;
-import org.apache.commons.math3.util.FastMath;
-
-/**
- * Base class for probability distributions on the reals.
- * Default implementations are provided for some of the methods
- * that do not vary from distribution to distribution.
- *
- * @since 3.0
- */
-public abstract class AbstractRealDistribution
-implements RealDistribution, Serializable {
- /** Default accuracy. */
- public static final double SOLVER_DEFAULT_ABSOLUTE_ACCURACY = 1e-6;
- /** Serializable version identifier */
- private static final long serialVersionUID = -38038050983108802L;
- /**
- * RandomData instance used to generate samples from the distribution.
- * @deprecated As of 3.1, to be removed in 4.0. Please use the
- * {@link #random} instance variable instead.
- */
- @Deprecated
- protected RandomDataImpl randomData = new RandomDataImpl();
-
- /**
- * RNG instance used to generate samples from the distribution.
- * @since 3.1
- */
- protected final RandomGenerator random;
-
- /** Solver absolute accuracy for inverse cumulative computation */
- private double solverAbsoluteAccuracy = SOLVER_DEFAULT_ABSOLUTE_ACCURACY;
-
- /**
- * @deprecated As of 3.1, to be removed in 4.0. Please use
- * {@link #AbstractRealDistribution(RandomGenerator)} instead.
- */
- @Deprecated
- protected AbstractRealDistribution() {
- // Legacy users are only allowed to access the deprecated "randomData".
- // New users are forbidden to use this constructor.
- random = null;
- }
- /**
- * @param rng Random number generator.
- * @since 3.1
- */
- protected AbstractRealDistribution(RandomGenerator rng) {
- random = rng;
- }
-
- /**
- * {@inheritDoc}
- *
- * The default implementation uses the identity
- * <p>{@code P(x0 < X <= x1) = P(X <= x1) - P(X <= x0)}</p>
- *
- * @deprecated As of 3.1 (to be removed in 4.0). Please use
- * {@link #probability(double,double)} instead.
- */
- @Deprecated
- public double cumulativeProbability(double x0, double x1) throws NumberIsTooLargeException {
- return probability(x0, x1);
- }
-
- /**
- * For a random variable {@code X} whose values are distributed according
- * to this distribution, this method returns {@code P(x0 < X <= x1)}.
- *
- * @param x0 Lower bound (excluded).
- * @param x1 Upper bound (included).
- * @return the probability that a random variable with this distribution
- * takes a value between {@code x0} and {@code x1}, excluding the lower
- * and including the upper endpoint.
- * @throws NumberIsTooLargeException if {@code x0 > x1}.
- *
- * The default implementation uses the identity
- * {@code P(x0 < X <= x1) = P(X <= x1) - P(X <= x0)}
- *
- * @since 3.1
- */
- public double probability(double x0,
- double x1) {
- if (x0 > x1) {
- throw new NumberIsTooLargeException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT,
- x0, x1, true);
- }
- return cumulativeProbability(x1) - cumulativeProbability(x0);
- }
-
- /**
- * {@inheritDoc}
- *
- * The default implementation returns
- * <ul>
- * <li>{@link #getSupportLowerBound()} for {@code p = 0},</li>
- * <li>{@link #getSupportUpperBound()} for {@code p = 1}.</li>
- * </ul>
- */
- public double inverseCumulativeProbability(final double p) throws OutOfRangeException {
- /*
- * IMPLEMENTATION NOTES
- * --------------------
- * Where applicable, use is made of the one-sided Chebyshev inequality
- * to bracket the root. This inequality states that
- * P(X - mu >= k * sig) <= 1 / (1 + k^2),
- * mu: mean, sig: standard deviation. Equivalently
- * 1 - P(X < mu + k * sig) <= 1 / (1 + k^2),
- * F(mu + k * sig) >= k^2 / (1 + k^2).
- *
- * For k = sqrt(p / (1 - p)), we find
- * F(mu + k * sig) >= p,
- * and (mu + k * sig) is an upper-bound for the root.
- *
- * Then, introducing Y = -X, mean(Y) = -mu, sd(Y) = sig, and
- * P(Y >= -mu + k * sig) <= 1 / (1 + k^2),
- * P(-X >= -mu + k * sig) <= 1 / (1 + k^2),
- * P(X <= mu - k * sig) <= 1 / (1 + k^2),
- * F(mu - k * sig) <= 1 / (1 + k^2).
- *
- * For k = sqrt((1 - p) / p), we find
- * F(mu - k * sig) <= p,
- * and (mu - k * sig) is a lower-bound for the root.
- *
- * In cases where the Chebyshev inequality does not apply, geometric
- * progressions 1, 2, 4, ... and -1, -2, -4, ... are used to bracket
- * the root.
- */
- if (p < 0.0 || p > 1.0) {
- throw new OutOfRangeException(p, 0, 1);
- }
-
- double lowerBound = getSupportLowerBound();
- if (p == 0.0) {
- return lowerBound;
- }
-
- double upperBound = getSupportUpperBound();
- if (p == 1.0) {
- return upperBound;
- }
-
- final double mu = getNumericalMean();
- final double sig = FastMath.sqrt(getNumericalVariance());
- final boolean chebyshevApplies;
- chebyshevApplies = !(Double.isInfinite(mu) || Double.isNaN(mu) ||
- Double.isInfinite(sig) || Double.isNaN(sig));
-
- if (lowerBound == Double.NEGATIVE_INFINITY) {
- if (chebyshevApplies) {
- lowerBound = mu - sig * FastMath.sqrt((1. - p) / p);
- } else {
- lowerBound = -1.0;
- while (cumulativeProbability(lowerBound) >= p) {
- lowerBound *= 2.0;
- }
- }
- }
-
- if (upperBound == Double.POSITIVE_INFINITY) {
- if (chebyshevApplies) {
- upperBound = mu + sig * FastMath.sqrt(p / (1. - p));
- } else {
- upperBound = 1.0;
- while (cumulativeProbability(upperBound) < p) {
- upperBound *= 2.0;
- }
- }
- }
-
- final UnivariateFunction toSolve = new UnivariateFunction() {
-
- public double value(final double x) {
- return cumulativeProbability(x) - p;
- }
- };
-
- double x = UnivariateSolverUtils.solve(toSolve,
- lowerBound,
- upperBound,
- getSolverAbsoluteAccuracy());
-
- if (!isSupportConnected()) {
- /* Test for plateau. */
- final double dx = getSolverAbsoluteAccuracy();
- if (x - dx >= getSupportLowerBound()) {
- double px = cumulativeProbability(x);
- if (cumulativeProbability(x - dx) == px) {
- upperBound = x;
- while (upperBound - lowerBound > dx) {
- final double midPoint = 0.5 * (lowerBound + upperBound);
- if (cumulativeProbability(midPoint) < px) {
- lowerBound = midPoint;
- } else {
- upperBound = midPoint;
- }
- }
- return upperBound;
- }
- }
- }
- return x;
- }
-
- /**
- * Returns the solver absolute accuracy for inverse cumulative computation.
- * You can override this method in order to use a Brent solver with an
- * absolute accuracy different from the default.
- *
- * @return the maximum absolute error in inverse cumulative probability estimates
- */
- protected double getSolverAbsoluteAccuracy() {
- return solverAbsoluteAccuracy;
- }
-
- /** {@inheritDoc} */
- public void reseedRandomGenerator(long seed) {
- random.setSeed(seed);
- randomData.reSeed(seed);
- }
-
- /**
- * {@inheritDoc}
- *
- * The default implementation uses the
- * <a href="http://en.wikipedia.org/wiki/Inverse_transform_sampling">
- * inversion method.
- * </a>
- */
- public double sample() {
- return inverseCumulativeProbability(random.nextDouble());
- }
-
- /**
- * {@inheritDoc}
- *
- * The default implementation generates the sample by calling
- * {@link #sample()} in a loop.
- */
- public double[] sample(int sampleSize) {
- if (sampleSize <= 0) {
- throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES,
- sampleSize);
- }
- double[] out = new double[sampleSize];
- for (int i = 0; i < sampleSize; i++) {
- out[i] = sample();
- }
- return out;
- }
-
- /**
- * {@inheritDoc}
- *
- * @return zero.
- * @since 3.1
- */
- public double probability(double x) {
- return 0d;
- }
-
- /**
- * Returns the natural logarithm of the probability density function (PDF) of this distribution
- * evaluated at the specified point {@code x}. In general, the PDF is the derivative of the
- * {@link #cumulativeProbability(double) CDF}. If the derivative does not exist at {@code x},
- * then an appropriate replacement should be returned, e.g. {@code Double.POSITIVE_INFINITY},
- * {@code Double.NaN}, or the limit inferior or limit superior of the difference quotient. Note
- * that due to the floating point precision and under/overflow issues, this method will for some
- * distributions be more precise and faster than computing the logarithm of
- * {@link #density(double)}. The default implementation simply computes the logarithm of
- * {@code density(x)}.
- *
- * @param x the point at which the PDF is evaluated
- * @return the logarithm of the value of the probability density function at point {@code x}
- */
- public double logDensity(double x) {
- return FastMath.log(density(x));
- }
-}
-
http://git-wip-us.apache.org/repos/asf/commons-math/blob/a7b4803f/src/main/java/org/apache/commons/math3/distribution/BetaDistribution.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/math3/distribution/BetaDistribution.java b/src/main/java/org/apache/commons/math3/distribution/BetaDistribution.java
deleted file mode 100644
index 3f62f64..0000000
--- a/src/main/java/org/apache/commons/math3/distribution/BetaDistribution.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.math3.distribution;
-
-import org.apache.commons.math3.exception.NumberIsTooSmallException;
-import org.apache.commons.math3.exception.util.LocalizedFormats;
-import org.apache.commons.math3.random.RandomGenerator;
-import org.apache.commons.math3.random.Well19937c;
-import org.apache.commons.math3.special.Beta;
-import org.apache.commons.math3.special.Gamma;
-import org.apache.commons.math3.util.FastMath;
-
-/**
- * Implements the Beta distribution.
- *
- * @see <a href="http://en.wikipedia.org/wiki/Beta_distribution">Beta distribution</a>
- * @since 2.0 (changed to concrete class in 3.0)
- */
-public class BetaDistribution extends AbstractRealDistribution {
- /**
- * Default inverse cumulative probability accuracy.
- * @since 2.1
- */
- public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
- /** Serializable version identifier. */
- private static final long serialVersionUID = -1221965979403477668L;
- /** First shape parameter. */
- private final double alpha;
- /** Second shape parameter. */
- private final double beta;
- /** Normalizing factor used in density computations.
- * updated whenever alpha or beta are changed.
- */
- private double z;
- /** Inverse cumulative probability accuracy. */
- private final double solverAbsoluteAccuracy;
-
- /**
- * Build a new instance.
- * <p>
- * <b>Note:</b> this constructor will implicitly create an instance of
- * {@link Well19937c} as random generator to be used for sampling only (see
- * {@link #sample()} and {@link #sample(int)}). In case no sampling is
- * needed for the created distribution, it is advised to pass {@code null}
- * as random generator via the appropriate constructors to avoid the
- * additional initialisation overhead.
- *
- * @param alpha First shape parameter (must be positive).
- * @param beta Second shape parameter (must be positive).
- */
- public BetaDistribution(double alpha, double beta) {
- this(alpha, beta, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
- }
-
- /**
- * Build a new instance.
- * <p>
- * <b>Note:</b> this constructor will implicitly create an instance of
- * {@link Well19937c} as random generator to be used for sampling only (see
- * {@link #sample()} and {@link #sample(int)}). In case no sampling is
- * needed for the created distribution, it is advised to pass {@code null}
- * as random generator via the appropriate constructors to avoid the
- * additional initialisation overhead.
- *
- * @param alpha First shape parameter (must be positive).
- * @param beta Second shape parameter (must be positive).
- * @param inverseCumAccuracy Maximum absolute error in inverse
- * cumulative probability estimates (defaults to
- * {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
- * @since 2.1
- */
- public BetaDistribution(double alpha, double beta, double inverseCumAccuracy) {
- this(new Well19937c(), alpha, beta, inverseCumAccuracy);
- }
-
- /**
- * Creates a β distribution.
- *
- * @param rng Random number generator.
- * @param alpha First shape parameter (must be positive).
- * @param beta Second shape parameter (must be positive).
- * @since 3.3
- */
- public BetaDistribution(RandomGenerator rng, double alpha, double beta) {
- this(rng, alpha, beta, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
- }
-
- /**
- * Creates a β distribution.
- *
- * @param rng Random number generator.
- * @param alpha First shape parameter (must be positive).
- * @param beta Second shape parameter (must be positive).
- * @param inverseCumAccuracy Maximum absolute error in inverse
- * cumulative probability estimates (defaults to
- * {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
- * @since 3.1
- */
- public BetaDistribution(RandomGenerator rng,
- double alpha,
- double beta,
- double inverseCumAccuracy) {
- super(rng);
-
- this.alpha = alpha;
- this.beta = beta;
- z = Double.NaN;
- solverAbsoluteAccuracy = inverseCumAccuracy;
- }
-
- /**
- * Access the first shape parameter, {@code alpha}.
- *
- * @return the first shape parameter.
- */
- public double getAlpha() {
- return alpha;
- }
-
- /**
- * Access the second shape parameter, {@code beta}.
- *
- * @return the second shape parameter.
- */
- public double getBeta() {
- return beta;
- }
-
- /** Recompute the normalization factor. */
- private void recomputeZ() {
- if (Double.isNaN(z)) {
- z = Gamma.logGamma(alpha) + Gamma.logGamma(beta) - Gamma.logGamma(alpha + beta);
- }
- }
-
- /** {@inheritDoc} */
- public double density(double x) {
- final double logDensity = logDensity(x);
- return logDensity == Double.NEGATIVE_INFINITY ? 0 : FastMath.exp(logDensity);
- }
-
- /** {@inheritDoc} **/
- @Override
- public double logDensity(double x) {
- recomputeZ();
- if (x < 0 || x > 1) {
- return Double.NEGATIVE_INFINITY;
- } else if (x == 0) {
- if (alpha < 1) {
- throw new NumberIsTooSmallException(LocalizedFormats.CANNOT_COMPUTE_BETA_DENSITY_AT_0_FOR_SOME_ALPHA, alpha, 1, false);
- }
- return Double.NEGATIVE_INFINITY;
- } else if (x == 1) {
- if (beta < 1) {
- throw new NumberIsTooSmallException(LocalizedFormats.CANNOT_COMPUTE_BETA_DENSITY_AT_1_FOR_SOME_BETA, beta, 1, false);
- }
- return Double.NEGATIVE_INFINITY;
- } else {
- double logX = FastMath.log(x);
- double log1mX = FastMath.log1p(-x);
- return (alpha - 1) * logX + (beta - 1) * log1mX - z;
- }
- }
-
- /** {@inheritDoc} */
- public double cumulativeProbability(double x) {
- if (x <= 0) {
- return 0;
- } else if (x >= 1) {
- return 1;
- } else {
- return Beta.regularizedBeta(x, alpha, beta);
- }
- }
-
- /**
- * Return the absolute accuracy setting of the solver used to estimate
- * inverse cumulative probabilities.
- *
- * @return the solver absolute accuracy.
- * @since 2.1
- */
- @Override
- protected double getSolverAbsoluteAccuracy() {
- return solverAbsoluteAccuracy;
- }
-
- /**
- * {@inheritDoc}
- *
- * For first shape parameter {@code alpha} and second shape parameter
- * {@code beta}, the mean is {@code alpha / (alpha + beta)}.
- */
- public double getNumericalMean() {
- final double a = getAlpha();
- return a / (a + getBeta());
- }
-
- /**
- * {@inheritDoc}
- *
- * For first shape parameter {@code alpha} and second shape parameter
- * {@code beta}, the variance is
- * {@code (alpha * beta) / [(alpha + beta)^2 * (alpha + beta + 1)]}.
- */
- public double getNumericalVariance() {
- final double a = getAlpha();
- final double b = getBeta();
- final double alphabetasum = a + b;
- return (a * b) / ((alphabetasum * alphabetasum) * (alphabetasum + 1));
- }
-
- /**
- * {@inheritDoc}
- *
- * The lower bound of the support is always 0 no matter the parameters.
- *
- * @return lower bound of the support (always 0)
- */
- public double getSupportLowerBound() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- *
- * The upper bound of the support is always 1 no matter the parameters.
- *
- * @return upper bound of the support (always 1)
- */
- public double getSupportUpperBound() {
- return 1;
- }
-
- /** {@inheritDoc} */
- public boolean isSupportLowerBoundInclusive() {
- return false;
- }
-
- /** {@inheritDoc} */
- public boolean isSupportUpperBoundInclusive() {
- return false;
- }
-
- /**
- * {@inheritDoc}
- *
- * The support of this distribution is connected.
- *
- * @return {@code true}
- */
- public boolean isSupportConnected() {
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/commons-math/blob/a7b4803f/src/main/java/org/apache/commons/math3/distribution/BinomialDistribution.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/math3/distribution/BinomialDistribution.java b/src/main/java/org/apache/commons/math3/distribution/BinomialDistribution.java
deleted file mode 100644
index f8cea26..0000000
--- a/src/main/java/org/apache/commons/math3/distribution/BinomialDistribution.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.math3.distribution;
-
-import org.apache.commons.math3.exception.NotPositiveException;
-import org.apache.commons.math3.exception.OutOfRangeException;
-import org.apache.commons.math3.exception.util.LocalizedFormats;
-import org.apache.commons.math3.random.RandomGenerator;
-import org.apache.commons.math3.random.Well19937c;
-import org.apache.commons.math3.special.Beta;
-import org.apache.commons.math3.util.FastMath;
-
-/**
- * Implementation of the binomial distribution.
- *
- * @see <a href="http://en.wikipedia.org/wiki/Binomial_distribution">Binomial distribution (Wikipedia)</a>
- * @see <a href="http://mathworld.wolfram.com/BinomialDistribution.html">Binomial Distribution (MathWorld)</a>
- */
-public class BinomialDistribution extends AbstractIntegerDistribution {
- /** Serializable version identifier. */
- private static final long serialVersionUID = 6751309484392813623L;
- /** The number of trials. */
- private final int numberOfTrials;
- /** The probability of success. */
- private final double probabilityOfSuccess;
-
- /**
- * Create a binomial distribution with the given number of trials and
- * probability of success.
- * <p>
- * <b>Note:</b> this constructor will implicitly create an instance of
- * {@link Well19937c} as random generator to be used for sampling only (see
- * {@link #sample()} and {@link #sample(int)}). In case no sampling is
- * needed for the created distribution, it is advised to pass {@code null}
- * as random generator via the appropriate constructors to avoid the
- * additional initialisation overhead.
- *
- * @param trials Number of trials.
- * @param p Probability of success.
- * @throws NotPositiveException if {@code trials < 0}.
- * @throws OutOfRangeException if {@code p < 0} or {@code p > 1}.
- */
- public BinomialDistribution(int trials, double p) {
- this(new Well19937c(), trials, p);
- }
-
- /**
- * Creates a binomial distribution.
- *
- * @param rng Random number generator.
- * @param trials Number of trials.
- * @param p Probability of success.
- * @throws NotPositiveException if {@code trials < 0}.
- * @throws OutOfRangeException if {@code p < 0} or {@code p > 1}.
- * @since 3.1
- */
- public BinomialDistribution(RandomGenerator rng,
- int trials,
- double p) {
- super(rng);
-
- if (trials < 0) {
- throw new NotPositiveException(LocalizedFormats.NUMBER_OF_TRIALS,
- trials);
- }
- if (p < 0 || p > 1) {
- throw new OutOfRangeException(p, 0, 1);
- }
-
- probabilityOfSuccess = p;
- numberOfTrials = trials;
- }
-
- /**
- * Access the number of trials for this distribution.
- *
- * @return the number of trials.
- */
- public int getNumberOfTrials() {
- return numberOfTrials;
- }
-
- /**
- * Access the probability of success for this distribution.
- *
- * @return the probability of success.
- */
- public double getProbabilityOfSuccess() {
- return probabilityOfSuccess;
- }
-
- /** {@inheritDoc} */
- public double probability(int x) {
- final double logProbability = logProbability(x);
- return logProbability == Double.NEGATIVE_INFINITY ? 0 : FastMath.exp(logProbability);
- }
-
- /** {@inheritDoc} **/
- @Override
- public double logProbability(int x) {
- if (numberOfTrials == 0) {
- return (x == 0) ? 0. : Double.NEGATIVE_INFINITY;
- }
- double ret;
- if (x < 0 || x > numberOfTrials) {
- ret = Double.NEGATIVE_INFINITY;
- } else {
- ret = SaddlePointExpansion.logBinomialProbability(x,
- numberOfTrials, probabilityOfSuccess,
- 1.0 - probabilityOfSuccess);
- }
- return ret;
- }
-
- /** {@inheritDoc} */
- public double cumulativeProbability(int x) {
- double ret;
- if (x < 0) {
- ret = 0.0;
- } else if (x >= numberOfTrials) {
- ret = 1.0;
- } else {
- ret = 1.0 - Beta.regularizedBeta(probabilityOfSuccess,
- x + 1.0, numberOfTrials - x);
- }
- return ret;
- }
-
- /**
- * {@inheritDoc}
- *
- * For {@code n} trials and probability parameter {@code p}, the mean is
- * {@code n * p}.
- */
- public double getNumericalMean() {
- return numberOfTrials * probabilityOfSuccess;
- }
-
- /**
- * {@inheritDoc}
- *
- * For {@code n} trials and probability parameter {@code p}, the variance is
- * {@code n * p * (1 - p)}.
- */
- public double getNumericalVariance() {
- final double p = probabilityOfSuccess;
- return numberOfTrials * p * (1 - p);
- }
-
- /**
- * {@inheritDoc}
- *
- * The lower bound of the support is always 0 except for the probability
- * parameter {@code p = 1}.
- *
- * @return lower bound of the support (0 or the number of trials)
- */
- public int getSupportLowerBound() {
- return probabilityOfSuccess < 1.0 ? 0 : numberOfTrials;
- }
-
- /**
- * {@inheritDoc}
- *
- * The upper bound of the support is the number of trials except for the
- * probability parameter {@code p = 0}.
- *
- * @return upper bound of the support (number of trials or 0)
- */
- public int getSupportUpperBound() {
- return probabilityOfSuccess > 0.0 ? numberOfTrials : 0;
- }
-
- /**
- * {@inheritDoc}
- *
- * The support of this distribution is connected.
- *
- * @return {@code true}
- */
- public boolean isSupportConnected() {
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/commons-math/blob/a7b4803f/src/main/java/org/apache/commons/math3/distribution/CauchyDistribution.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/math3/distribution/CauchyDistribution.java b/src/main/java/org/apache/commons/math3/distribution/CauchyDistribution.java
deleted file mode 100644
index af3d33a..0000000
--- a/src/main/java/org/apache/commons/math3/distribution/CauchyDistribution.java
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.math3.distribution;
-
-import org.apache.commons.math3.exception.NotStrictlyPositiveException;
-import org.apache.commons.math3.exception.OutOfRangeException;
-import org.apache.commons.math3.exception.util.LocalizedFormats;
-import org.apache.commons.math3.random.RandomGenerator;
-import org.apache.commons.math3.random.Well19937c;
-import org.apache.commons.math3.util.FastMath;
-
-/**
- * Implementation of the Cauchy distribution.
- *
- * @see <a href="http://en.wikipedia.org/wiki/Cauchy_distribution">Cauchy distribution (Wikipedia)</a>
- * @see <a href="http://mathworld.wolfram.com/CauchyDistribution.html">Cauchy Distribution (MathWorld)</a>
- * @since 1.1 (changed to concrete class in 3.0)
- */
-public class CauchyDistribution extends AbstractRealDistribution {
- /**
- * Default inverse cumulative probability accuracy.
- * @since 2.1
- */
- public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
- /** Serializable version identifier */
- private static final long serialVersionUID = 8589540077390120676L;
- /** The median of this distribution. */
- private final double median;
- /** The scale of this distribution. */
- private final double scale;
- /** Inverse cumulative probability accuracy */
- private final double solverAbsoluteAccuracy;
-
- /**
- * Creates a Cauchy distribution with the median equal to zero and scale
- * equal to one.
- */
- public CauchyDistribution() {
- this(0, 1);
- }
-
- /**
- * Creates a Cauchy distribution using the given median and scale.
- * <p>
- * <b>Note:</b> this constructor will implicitly create an instance of
- * {@link Well19937c} as random generator to be used for sampling only (see
- * {@link #sample()} and {@link #sample(int)}). In case no sampling is
- * needed for the created distribution, it is advised to pass {@code null}
- * as random generator via the appropriate constructors to avoid the
- * additional initialisation overhead.
- *
- * @param median Median for this distribution.
- * @param scale Scale parameter for this distribution.
- */
- public CauchyDistribution(double median, double scale) {
- this(median, scale, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
- }
-
- /**
- * Creates a Cauchy distribution using the given median and scale.
- * <p>
- * <b>Note:</b> this constructor will implicitly create an instance of
- * {@link Well19937c} as random generator to be used for sampling only (see
- * {@link #sample()} and {@link #sample(int)}). In case no sampling is
- * needed for the created distribution, it is advised to pass {@code null}
- * as random generator via the appropriate constructors to avoid the
- * additional initialisation overhead.
- *
- * @param median Median for this distribution.
- * @param scale Scale parameter for this distribution.
- * @param inverseCumAccuracy Maximum absolute error in inverse
- * cumulative probability estimates
- * (defaults to {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
- * @throws NotStrictlyPositiveException if {@code scale <= 0}.
- * @since 2.1
- */
- public CauchyDistribution(double median, double scale,
- double inverseCumAccuracy) {
- this(new Well19937c(), median, scale, inverseCumAccuracy);
- }
-
- /**
- * Creates a Cauchy distribution.
- *
- * @param rng Random number generator.
- * @param median Median for this distribution.
- * @param scale Scale parameter for this distribution.
- * @throws NotStrictlyPositiveException if {@code scale <= 0}.
- * @since 3.3
- */
- public CauchyDistribution(RandomGenerator rng, double median, double scale) {
- this(rng, median, scale, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
- }
-
- /**
- * Creates a Cauchy distribution.
- *
- * @param rng Random number generator.
- * @param median Median for this distribution.
- * @param scale Scale parameter for this distribution.
- * @param inverseCumAccuracy Maximum absolute error in inverse
- * cumulative probability estimates
- * (defaults to {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
- * @throws NotStrictlyPositiveException if {@code scale <= 0}.
- * @since 3.1
- */
- public CauchyDistribution(RandomGenerator rng,
- double median,
- double scale,
- double inverseCumAccuracy) {
- super(rng);
- if (scale <= 0) {
- throw new NotStrictlyPositiveException(LocalizedFormats.SCALE, scale);
- }
- this.scale = scale;
- this.median = median;
- solverAbsoluteAccuracy = inverseCumAccuracy;
- }
-
- /** {@inheritDoc} */
- public double cumulativeProbability(double x) {
- return 0.5 + (FastMath.atan((x - median) / scale) / FastMath.PI);
- }
-
- /**
- * Access the median.
- *
- * @return the median for this distribution.
- */
- public double getMedian() {
- return median;
- }
-
- /**
- * Access the scale parameter.
- *
- * @return the scale parameter for this distribution.
- */
- public double getScale() {
- return scale;
- }
-
- /** {@inheritDoc} */
- public double density(double x) {
- final double dev = x - median;
- return (1 / FastMath.PI) * (scale / (dev * dev + scale * scale));
- }
-
- /**
- * {@inheritDoc}
- *
- * Returns {@code Double.NEGATIVE_INFINITY} when {@code p == 0}
- * and {@code Double.POSITIVE_INFINITY} when {@code p == 1}.
- */
- @Override
- public double inverseCumulativeProbability(double p) throws OutOfRangeException {
- double ret;
- if (p < 0 || p > 1) {
- throw new OutOfRangeException(p, 0, 1);
- } else if (p == 0) {
- ret = Double.NEGATIVE_INFINITY;
- } else if (p == 1) {
- ret = Double.POSITIVE_INFINITY;
- } else {
- ret = median + scale * FastMath.tan(FastMath.PI * (p - .5));
- }
- return ret;
- }
-
- /** {@inheritDoc} */
- @Override
- protected double getSolverAbsoluteAccuracy() {
- return solverAbsoluteAccuracy;
- }
-
- /**
- * {@inheritDoc}
- *
- * The mean is always undefined no matter the parameters.
- *
- * @return mean (always Double.NaN)
- */
- public double getNumericalMean() {
- return Double.NaN;
- }
-
- /**
- * {@inheritDoc}
- *
- * The variance is always undefined no matter the parameters.
- *
- * @return variance (always Double.NaN)
- */
- public double getNumericalVariance() {
- return Double.NaN;
- }
-
- /**
- * {@inheritDoc}
- *
- * The lower bound of the support is always negative infinity no matter
- * the parameters.
- *
- * @return lower bound of the support (always Double.NEGATIVE_INFINITY)
- */
- public double getSupportLowerBound() {
- return Double.NEGATIVE_INFINITY;
- }
-
- /**
- * {@inheritDoc}
- *
- * The upper bound of the support is always positive infinity no matter
- * the parameters.
- *
- * @return upper bound of the support (always Double.POSITIVE_INFINITY)
- */
- public double getSupportUpperBound() {
- return Double.POSITIVE_INFINITY;
- }
-
- /** {@inheritDoc} */
- public boolean isSupportLowerBoundInclusive() {
- return false;
- }
-
- /** {@inheritDoc} */
- public boolean isSupportUpperBoundInclusive() {
- return false;
- }
-
- /**
- * {@inheritDoc}
- *
- * The support of this distribution is connected.
- *
- * @return {@code true}
- */
- public boolean isSupportConnected() {
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/commons-math/blob/a7b4803f/src/main/java/org/apache/commons/math3/distribution/ChiSquaredDistribution.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/math3/distribution/ChiSquaredDistribution.java b/src/main/java/org/apache/commons/math3/distribution/ChiSquaredDistribution.java
deleted file mode 100644
index 393d352..0000000
--- a/src/main/java/org/apache/commons/math3/distribution/ChiSquaredDistribution.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.math3.distribution;
-
-import org.apache.commons.math3.random.RandomGenerator;
-import org.apache.commons.math3.random.Well19937c;
-
-/**
- * Implementation of the chi-squared distribution.
- *
- * @see <a href="http://en.wikipedia.org/wiki/Chi-squared_distribution">Chi-squared distribution (Wikipedia)</a>
- * @see <a href="http://mathworld.wolfram.com/Chi-SquaredDistribution.html">Chi-squared Distribution (MathWorld)</a>
- */
-public class ChiSquaredDistribution extends AbstractRealDistribution {
- /**
- * Default inverse cumulative probability accuracy
- * @since 2.1
- */
- public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
- /** Serializable version identifier */
- private static final long serialVersionUID = -8352658048349159782L;
- /** Internal Gamma distribution. */
- private final GammaDistribution gamma;
- /** Inverse cumulative probability accuracy */
- private final double solverAbsoluteAccuracy;
-
- /**
- * Create a Chi-Squared distribution with the given degrees of freedom.
- *
- * @param degreesOfFreedom Degrees of freedom.
- */
- public ChiSquaredDistribution(double degreesOfFreedom) {
- this(degreesOfFreedom, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
- }
-
- /**
- * Create a Chi-Squared distribution with the given degrees of freedom and
- * inverse cumulative probability accuracy.
- * <p>
- * <b>Note:</b> this constructor will implicitly create an instance of
- * {@link Well19937c} as random generator to be used for sampling only (see
- * {@link #sample()} and {@link #sample(int)}). In case no sampling is
- * needed for the created distribution, it is advised to pass {@code null}
- * as random generator via the appropriate constructors to avoid the
- * additional initialisation overhead.
- *
- * @param degreesOfFreedom Degrees of freedom.
- * @param inverseCumAccuracy the maximum absolute error in inverse
- * cumulative probability estimates (defaults to
- * {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
- * @since 2.1
- */
- public ChiSquaredDistribution(double degreesOfFreedom,
- double inverseCumAccuracy) {
- this(new Well19937c(), degreesOfFreedom, inverseCumAccuracy);
- }
-
- /**
- * Create a Chi-Squared distribution with the given degrees of freedom.
- *
- * @param rng Random number generator.
- * @param degreesOfFreedom Degrees of freedom.
- * @since 3.3
- */
- public ChiSquaredDistribution(RandomGenerator rng, double degreesOfFreedom) {
- this(rng, degreesOfFreedom, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
- }
-
- /**
- * Create a Chi-Squared distribution with the given degrees of freedom and
- * inverse cumulative probability accuracy.
- *
- * @param rng Random number generator.
- * @param degreesOfFreedom Degrees of freedom.
- * @param inverseCumAccuracy the maximum absolute error in inverse
- * cumulative probability estimates (defaults to
- * {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
- * @since 3.1
- */
- public ChiSquaredDistribution(RandomGenerator rng,
- double degreesOfFreedom,
- double inverseCumAccuracy) {
- super(rng);
-
- gamma = new GammaDistribution(degreesOfFreedom / 2, 2);
- solverAbsoluteAccuracy = inverseCumAccuracy;
- }
-
- /**
- * Access the number of degrees of freedom.
- *
- * @return the degrees of freedom.
- */
- public double getDegreesOfFreedom() {
- return gamma.getShape() * 2.0;
- }
-
- /** {@inheritDoc} */
- public double density(double x) {
- return gamma.density(x);
- }
-
- /** {@inheritDoc} **/
- @Override
- public double logDensity(double x) {
- return gamma.logDensity(x);
- }
-
- /** {@inheritDoc} */
- public double cumulativeProbability(double x) {
- return gamma.cumulativeProbability(x);
- }
-
- /** {@inheritDoc} */
- @Override
- protected double getSolverAbsoluteAccuracy() {
- return solverAbsoluteAccuracy;
- }
-
- /**
- * {@inheritDoc}
- *
- * For {@code k} degrees of freedom, the mean is {@code k}.
- */
- public double getNumericalMean() {
- return getDegreesOfFreedom();
- }
-
- /**
- * {@inheritDoc}
- *
- * @return {@code 2 * k}, where {@code k} is the number of degrees of freedom.
- */
- public double getNumericalVariance() {
- return 2 * getDegreesOfFreedom();
- }
-
- /**
- * {@inheritDoc}
- *
- * The lower bound of the support is always 0 no matter the
- * degrees of freedom.
- *
- * @return zero.
- */
- public double getSupportLowerBound() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- *
- * The upper bound of the support is always positive infinity no matter the
- * degrees of freedom.
- *
- * @return {@code Double.POSITIVE_INFINITY}.
- */
- public double getSupportUpperBound() {
- return Double.POSITIVE_INFINITY;
- }
-
- /** {@inheritDoc} */
- public boolean isSupportLowerBoundInclusive() {
- return true;
- }
-
- /** {@inheritDoc} */
- public boolean isSupportUpperBoundInclusive() {
- return false;
- }
-
- /**
- * {@inheritDoc}
- *
- * The support of this distribution is connected.
- *
- * @return {@code true}
- */
- public boolean isSupportConnected() {
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/commons-math/blob/a7b4803f/src/main/java/org/apache/commons/math3/distribution/ConstantRealDistribution.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/math3/distribution/ConstantRealDistribution.java b/src/main/java/org/apache/commons/math3/distribution/ConstantRealDistribution.java
deleted file mode 100644
index 0dbb6aa..0000000
--- a/src/main/java/org/apache/commons/math3/distribution/ConstantRealDistribution.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.commons.math3.distribution;
-
-import org.apache.commons.math3.exception.OutOfRangeException;
-
-/**
- * Implementation of the constant real distribution.
- *
- * @since 3.4
- */
-public class ConstantRealDistribution extends AbstractRealDistribution {
-
- /** Serialization ID */
- private static final long serialVersionUID = -4157745166772046273L;
-
- /** Constant value of the distribution */
- private final double value;
-
- /**
- * Create a constant real distribution with the given value.
- *
- * @param value the constant value of this distribution
- */
- public ConstantRealDistribution(double value) {
- super(null); // Avoid creating RandomGenerator
- this.value = value;
- }
-
- /** {@inheritDoc} */
- public double density(double x) {
- return x == value ? 1 : 0;
- }
-
- /** {@inheritDoc} */
- public double cumulativeProbability(double x) {
- return x < value ? 0 : 1;
- }
-
- @Override
- public double inverseCumulativeProbability(final double p)
- throws OutOfRangeException {
- if (p < 0.0 || p > 1.0) {
- throw new OutOfRangeException(p, 0, 1);
- }
- return value;
- }
-
- /**
- * {@inheritDoc}
- */
- public double getNumericalMean() {
- return value;
- }
-
- /**
- * {@inheritDoc}
- */
- public double getNumericalVariance() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public double getSupportLowerBound() {
- return value;
- }
-
- /**
- * {@inheritDoc}
- */
- public double getSupportUpperBound() {
- return value;
- }
-
- /** {@inheritDoc} */
- public boolean isSupportLowerBoundInclusive() {
- return true;
- }
-
- /** {@inheritDoc} */
- public boolean isSupportUpperBoundInclusive() {
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isSupportConnected() {
- return true;
- }
-
- /** {@inheritDoc} */
- @Override
- public double sample() {
- return value;
- }
-
- /**
- * Override with no-op (there is no generator).
- * @param seed (ignored)
- */
- @Override
- public void reseedRandomGenerator(long seed) {}
-}
http://git-wip-us.apache.org/repos/asf/commons-math/blob/a7b4803f/src/main/java/org/apache/commons/math3/distribution/EnumeratedDistribution.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/math3/distribution/EnumeratedDistribution.java b/src/main/java/org/apache/commons/math3/distribution/EnumeratedDistribution.java
deleted file mode 100644
index 4cb23c1..0000000
--- a/src/main/java/org/apache/commons/math3/distribution/EnumeratedDistribution.java
+++ /dev/null
@@ -1,291 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.math3.distribution;
-
-import java.io.Serializable;
-import java.lang.reflect.Array;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.commons.math3.exception.MathArithmeticException;
-import org.apache.commons.math3.exception.NotANumberException;
-import org.apache.commons.math3.exception.NotFiniteNumberException;
-import org.apache.commons.math3.exception.NotPositiveException;
-import org.apache.commons.math3.exception.NotStrictlyPositiveException;
-import org.apache.commons.math3.exception.NullArgumentException;
-import org.apache.commons.math3.exception.util.LocalizedFormats;
-import org.apache.commons.math3.random.RandomGenerator;
-import org.apache.commons.math3.random.Well19937c;
-import org.apache.commons.math3.util.MathArrays;
-import org.apache.commons.math3.util.Pair;
-
-/**
- * <p>A generic implementation of a
- * <a href="http://en.wikipedia.org/wiki/Probability_distribution#Discrete_probability_distribution">
- * discrete probability distribution (Wikipedia)</a> over a finite sample space,
- * based on an enumerated list of <value, probability> pairs. Input probabilities must all be non-negative,
- * but zero values are allowed and their sum does not have to equal one. Constructors will normalize input
- * probabilities to make them sum to one.</p>
- *
- * <p>The list of <value, probability> pairs does not, strictly speaking, have to be a function and it can
- * contain null values. The pmf created by the constructor will combine probabilities of equal values and
- * will treat null values as equal. For example, if the list of pairs <"dog", 0.2>, <null, 0.1>,
- * <"pig", 0.2>, <"dog", 0.1>, <null, 0.4> is provided to the constructor, the resulting
- * pmf will assign mass of 0.5 to null, 0.3 to "dog" and 0.2 to null.</p>
- *
- * @param <T> type of the elements in the sample space.
- * @since 3.2
- */
-public class EnumeratedDistribution<T> implements Serializable {
-
- /** Serializable UID. */
- private static final long serialVersionUID = 20123308L;
-
- /**
- * RNG instance used to generate samples from the distribution.
- */
- protected final RandomGenerator random;
-
- /**
- * List of random variable values.
- */
- private final List<T> singletons;
-
- /**
- * Probabilities of respective random variable values. For i = 0, ..., singletons.size() - 1,
- * probability[i] is the probability that a random variable following this distribution takes
- * the value singletons[i].
- */
- private final double[] probabilities;
-
- /**
- * Cumulative probabilities, cached to speed up sampling.
- */
- private final double[] cumulativeProbabilities;
-
- /**
- * Create an enumerated distribution using the given probability mass function
- * enumeration.
- * <p>
- * <b>Note:</b> this constructor will implicitly create an instance of
- * {@link Well19937c} as random generator to be used for sampling only (see
- * {@link #sample()} and {@link #sample(int)}). In case no sampling is
- * needed for the created distribution, it is advised to pass {@code null}
- * as random generator via the appropriate constructors to avoid the
- * additional initialisation overhead.
- *
- * @param pmf probability mass function enumerated as a list of <T, probability>
- * pairs.
- * @throws NotPositiveException if any of the probabilities are negative.
- * @throws NotFiniteNumberException if any of the probabilities are infinite.
- * @throws NotANumberException if any of the probabilities are NaN.
- * @throws MathArithmeticException all of the probabilities are 0.
- */
- public EnumeratedDistribution(final List<Pair<T, Double>> pmf)
- throws NotPositiveException, MathArithmeticException, NotFiniteNumberException, NotANumberException {
- this(new Well19937c(), pmf);
- }
-
- /**
- * Create an enumerated distribution using the given random number generator
- * and probability mass function enumeration.
- *
- * @param rng random number generator.
- * @param pmf probability mass function enumerated as a list of <T, probability>
- * pairs.
- * @throws NotPositiveException if any of the probabilities are negative.
- * @throws NotFiniteNumberException if any of the probabilities are infinite.
- * @throws NotANumberException if any of the probabilities are NaN.
- * @throws MathArithmeticException all of the probabilities are 0.
- */
- public EnumeratedDistribution(final RandomGenerator rng, final List<Pair<T, Double>> pmf)
- throws NotPositiveException, MathArithmeticException, NotFiniteNumberException, NotANumberException {
- random = rng;
-
- singletons = new ArrayList<T>(pmf.size());
- final double[] probs = new double[pmf.size()];
-
- for (int i = 0; i < pmf.size(); i++) {
- final Pair<T, Double> sample = pmf.get(i);
- singletons.add(sample.getKey());
- final double p = sample.getValue();
- if (p < 0) {
- throw new NotPositiveException(sample.getValue());
- }
- if (Double.isInfinite(p)) {
- throw new NotFiniteNumberException(p);
- }
- if (Double.isNaN(p)) {
- throw new NotANumberException();
- }
- probs[i] = p;
- }
-
- probabilities = MathArrays.normalizeArray(probs, 1.0);
-
- cumulativeProbabilities = new double[probabilities.length];
- double sum = 0;
- for (int i = 0; i < probabilities.length; i++) {
- sum += probabilities[i];
- cumulativeProbabilities[i] = sum;
- }
- }
-
- /**
- * Reseed the random generator used to generate samples.
- *
- * @param seed the new seed
- */
- public void reseedRandomGenerator(long seed) {
- random.setSeed(seed);
- }
-
- /**
- * <p>For a random variable {@code X} whose values are distributed according to
- * this distribution, this method returns {@code P(X = x)}. In other words,
- * this method represents the probability mass function (PMF) for the
- * distribution.</p>
- *
- * <p>Note that if {@code x1} and {@code x2} satisfy {@code x1.equals(x2)},
- * or both are null, then {@code probability(x1) = probability(x2)}.</p>
- *
- * @param x the point at which the PMF is evaluated
- * @return the value of the probability mass function at {@code x}
- */
- double probability(final T x) {
- double probability = 0;
-
- for (int i = 0; i < probabilities.length; i++) {
- if ((x == null && singletons.get(i) == null) ||
- (x != null && x.equals(singletons.get(i)))) {
- probability += probabilities[i];
- }
- }
-
- return probability;
- }
-
- /**
- * <p>Return the probability mass function as a list of <value, probability> pairs.</p>
- *
- * <p>Note that if duplicate and / or null values were provided to the constructor
- * when creating this EnumeratedDistribution, the returned list will contain these
- * values. If duplicates values exist, what is returned will not represent
- * a pmf (i.e., it is up to the caller to consolidate duplicate mass points).</p>
- *
- * @return the probability mass function.
- */
- public List<Pair<T, Double>> getPmf() {
- final List<Pair<T, Double>> samples = new ArrayList<Pair<T, Double>>(probabilities.length);
-
- for (int i = 0; i < probabilities.length; i++) {
- samples.add(new Pair<T, Double>(singletons.get(i), probabilities[i]));
- }
-
- return samples;
- }
-
- /**
- * Generate a random value sampled from this distribution.
- *
- * @return a random value.
- */
- public T sample() {
- final double randomValue = random.nextDouble();
-
- int index = Arrays.binarySearch(cumulativeProbabilities, randomValue);
- if (index < 0) {
- index = -index-1;
- }
-
- if (index >= 0 && index < probabilities.length) {
- if (randomValue < cumulativeProbabilities[index]) {
- return singletons.get(index);
- }
- }
-
- /* This should never happen, but it ensures we will return a correct
- * object in case there is some floating point inequality problem
- * wrt the cumulative probabilities. */
- return singletons.get(singletons.size() - 1);
- }
-
- /**
- * Generate a random sample from the distribution.
- *
- * @param sampleSize the number of random values to generate.
- * @return an array representing the random sample.
- * @throws NotStrictlyPositiveException if {@code sampleSize} is not
- * positive.
- */
- public Object[] sample(int sampleSize) throws NotStrictlyPositiveException {
- if (sampleSize <= 0) {
- throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES,
- sampleSize);
- }
-
- final Object[] out = new Object[sampleSize];
-
- for (int i = 0; i < sampleSize; i++) {
- out[i] = sample();
- }
-
- return out;
-
- }
-
- /**
- * Generate a random sample from the distribution.
- * <p>
- * If the requested samples fit in the specified array, it is returned
- * therein. Otherwise, a new array is allocated with the runtime type of
- * the specified array and the size of this collection.
- *
- * @param sampleSize the number of random values to generate.
- * @param array the array to populate.
- * @return an array representing the random sample.
- * @throws NotStrictlyPositiveException if {@code sampleSize} is not positive.
- * @throws NullArgumentException if {@code array} is null
- */
- public T[] sample(int sampleSize, final T[] array) throws NotStrictlyPositiveException {
- if (sampleSize <= 0) {
- throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES, sampleSize);
- }
-
- if (array == null) {
- throw new NullArgumentException(LocalizedFormats.INPUT_ARRAY);
- }
-
- T[] out;
- if (array.length < sampleSize) {
- @SuppressWarnings("unchecked") // safe as both are of type T
- final T[] unchecked = (T[]) Array.newInstance(array.getClass().getComponentType(), sampleSize);
- out = unchecked;
- } else {
- out = array;
- }
-
- for (int i = 0; i < sampleSize; i++) {
- out[i] = sample();
- }
-
- return out;
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/commons-math/blob/a7b4803f/src/main/java/org/apache/commons/math3/distribution/EnumeratedIntegerDistribution.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/math3/distribution/EnumeratedIntegerDistribution.java b/src/main/java/org/apache/commons/math3/distribution/EnumeratedIntegerDistribution.java
deleted file mode 100644
index 9a07787..0000000
--- a/src/main/java/org/apache/commons/math3/distribution/EnumeratedIntegerDistribution.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.math3.distribution;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.math3.exception.DimensionMismatchException;
-import org.apache.commons.math3.exception.MathArithmeticException;
-import org.apache.commons.math3.exception.NotANumberException;
-import org.apache.commons.math3.exception.NotFiniteNumberException;
-import org.apache.commons.math3.exception.NotPositiveException;
-import org.apache.commons.math3.random.RandomGenerator;
-import org.apache.commons.math3.random.Well19937c;
-import org.apache.commons.math3.util.Pair;
-
-/**
- * <p>Implementation of an integer-valued {@link EnumeratedDistribution}.</p>
- *
- * <p>Values with zero-probability are allowed but they do not extend the
- * support.<br/>
- * Duplicate values are allowed. Probabilities of duplicate values are combined
- * when computing cumulative probabilities and statistics.</p>
- *
- * @since 3.2
- */
-public class EnumeratedIntegerDistribution extends AbstractIntegerDistribution {
-
- /** Serializable UID. */
- private static final long serialVersionUID = 20130308L;
-
- /**
- * {@link EnumeratedDistribution} instance (using the {@link Integer} wrapper)
- * used to generate the pmf.
- */
- protected final EnumeratedDistribution<Integer> innerDistribution;
-
- /**
- * Create a discrete distribution using the given probability mass function
- * definition.
- * <p>
- * <b>Note:</b> this constructor will implicitly create an instance of
- * {@link Well19937c} as random generator to be used for sampling only (see
- * {@link #sample()} and {@link #sample(int)}). In case no sampling is
- * needed for the created distribution, it is advised to pass {@code null}
- * as random generator via the appropriate constructors to avoid the
- * additional initialisation overhead.
- *
- * @param singletons array of random variable values.
- * @param probabilities array of probabilities.
- * @throws DimensionMismatchException if
- * {@code singletons.length != probabilities.length}
- * @throws NotPositiveException if any of the probabilities are negative.
- * @throws NotFiniteNumberException if any of the probabilities are infinite.
- * @throws NotANumberException if any of the probabilities are NaN.
- * @throws MathArithmeticException all of the probabilities are 0.
- */
- public EnumeratedIntegerDistribution(final int[] singletons, final double[] probabilities)
- throws DimensionMismatchException, NotPositiveException, MathArithmeticException,
- NotFiniteNumberException, NotANumberException{
- this(new Well19937c(), singletons, probabilities);
- }
-
- /**
- * Create a discrete distribution using the given random number generator
- * and probability mass function definition.
- *
- * @param rng random number generator.
- * @param singletons array of random variable values.
- * @param probabilities array of probabilities.
- * @throws DimensionMismatchException if
- * {@code singletons.length != probabilities.length}
- * @throws NotPositiveException if any of the probabilities are negative.
- * @throws NotFiniteNumberException if any of the probabilities are infinite.
- * @throws NotANumberException if any of the probabilities are NaN.
- * @throws MathArithmeticException all of the probabilities are 0.
- */
- public EnumeratedIntegerDistribution(final RandomGenerator rng,
- final int[] singletons, final double[] probabilities)
- throws DimensionMismatchException, NotPositiveException, MathArithmeticException,
- NotFiniteNumberException, NotANumberException {
- super(rng);
- if (singletons.length != probabilities.length) {
- throw new DimensionMismatchException(probabilities.length, singletons.length);
- }
-
- final List<Pair<Integer, Double>> samples = new ArrayList<Pair<Integer, Double>>(singletons.length);
-
- for (int i = 0; i < singletons.length; i++) {
- samples.add(new Pair<Integer, Double>(singletons[i], probabilities[i]));
- }
-
- innerDistribution = new EnumeratedDistribution<Integer>(rng, samples);
- }
-
- /**
- * {@inheritDoc}
- */
- public double probability(final int x) {
- return innerDistribution.probability(x);
- }
-
- /**
- * {@inheritDoc}
- */
- public double cumulativeProbability(final int x) {
- double probability = 0;
-
- for (final Pair<Integer, Double> sample : innerDistribution.getPmf()) {
- if (sample.getKey() <= x) {
- probability += sample.getValue();
- }
- }
-
- return probability;
- }
-
- /**
- * {@inheritDoc}
- *
- * @return {@code sum(singletons[i] * probabilities[i])}
- */
- public double getNumericalMean() {
- double mean = 0;
-
- for (final Pair<Integer, Double> sample : innerDistribution.getPmf()) {
- mean += sample.getValue() * sample.getKey();
- }
-
- return mean;
- }
-
- /**
- * {@inheritDoc}
- *
- * @return {@code sum((singletons[i] - mean) ^ 2 * probabilities[i])}
- */
- public double getNumericalVariance() {
- double mean = 0;
- double meanOfSquares = 0;
-
- for (final Pair<Integer, Double> sample : innerDistribution.getPmf()) {
- mean += sample.getValue() * sample.getKey();
- meanOfSquares += sample.getValue() * sample.getKey() * sample.getKey();
- }
-
- return meanOfSquares - mean * mean;
- }
-
- /**
- * {@inheritDoc}
- *
- * Returns the lowest value with non-zero probability.
- *
- * @return the lowest value with non-zero probability.
- */
- public int getSupportLowerBound() {
- int min = Integer.MAX_VALUE;
- for (final Pair<Integer, Double> sample : innerDistribution.getPmf()) {
- if (sample.getKey() < min && sample.getValue() > 0) {
- min = sample.getKey();
- }
- }
-
- return min;
- }
-
- /**
- * {@inheritDoc}
- *
- * Returns the highest value with non-zero probability.
- *
- * @return the highest value with non-zero probability.
- */
- public int getSupportUpperBound() {
- int max = Integer.MIN_VALUE;
- for (final Pair<Integer, Double> sample : innerDistribution.getPmf()) {
- if (sample.getKey() > max && sample.getValue() > 0) {
- max = sample.getKey();
- }
- }
-
- return max;
- }
-
- /**
- * {@inheritDoc}
- *
- * The support of this distribution is connected.
- *
- * @return {@code true}
- */
- public boolean isSupportConnected() {
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int sample() {
- return innerDistribution.sample();
- }
-}
http://git-wip-us.apache.org/repos/asf/commons-math/blob/a7b4803f/src/main/java/org/apache/commons/math3/distribution/EnumeratedRealDistribution.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/commons/math3/distribution/EnumeratedRealDistribution.java b/src/main/java/org/apache/commons/math3/distribution/EnumeratedRealDistribution.java
deleted file mode 100644
index 07b96bc..0000000
--- a/src/main/java/org/apache/commons/math3/distribution/EnumeratedRealDistribution.java
+++ /dev/null
@@ -1,282 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.math3.distribution;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.math3.exception.DimensionMismatchException;
-import org.apache.commons.math3.exception.MathArithmeticException;
-import org.apache.commons.math3.exception.NotANumberException;
-import org.apache.commons.math3.exception.NotFiniteNumberException;
-import org.apache.commons.math3.exception.NotPositiveException;
-import org.apache.commons.math3.exception.OutOfRangeException;
-import org.apache.commons.math3.random.RandomGenerator;
-import org.apache.commons.math3.random.Well19937c;
-import org.apache.commons.math3.util.Pair;
-
-/**
- * <p>Implementation of a real-valued {@link EnumeratedDistribution}.
- *
- * <p>Values with zero-probability are allowed but they do not extend the
- * support.<br/>
- * Duplicate values are allowed. Probabilities of duplicate values are combined
- * when computing cumulative probabilities and statistics.</p>
- *
- * @since 3.2
- */
-public class EnumeratedRealDistribution extends AbstractRealDistribution {
-
- /** Serializable UID. */
- private static final long serialVersionUID = 20130308L;
-
- /**
- * {@link EnumeratedDistribution} (using the {@link Double} wrapper)
- * used to generate the pmf.
- */
- protected final EnumeratedDistribution<Double> innerDistribution;
-
- /**
- * Create a discrete distribution using the given probability mass function
- * enumeration.
- * <p>
- * <b>Note:</b> this constructor will implicitly create an instance of
- * {@link Well19937c} as random generator to be used for sampling only (see
- * {@link #sample()} and {@link #sample(int)}). In case no sampling is
- * needed for the created distribution, it is advised to pass {@code null}
- * as random generator via the appropriate constructors to avoid the
- * additional initialisation overhead.
- *
- * @param singletons array of random variable values.
- * @param probabilities array of probabilities.
- * @throws DimensionMismatchException if
- * {@code singletons.length != probabilities.length}
- * @throws NotPositiveException if any of the probabilities are negative.
- * @throws NotFiniteNumberException if any of the probabilities are infinite.
- * @throws NotANumberException if any of the probabilities are NaN.
- * @throws MathArithmeticException all of the probabilities are 0.
- */
- public EnumeratedRealDistribution(final double[] singletons, final double[] probabilities)
- throws DimensionMismatchException, NotPositiveException, MathArithmeticException,
- NotFiniteNumberException, NotANumberException {
- this(new Well19937c(), singletons, probabilities);
- }
-
- /**
- * Create a discrete distribution using the given random number generator
- * and probability mass function enumeration.
- *
- * @param rng random number generator.
- * @param singletons array of random variable values.
- * @param probabilities array of probabilities.
- * @throws DimensionMismatchException if
- * {@code singletons.length != probabilities.length}
- * @throws NotPositiveException if any of the probabilities are negative.
- * @throws NotFiniteNumberException if any of the probabilities are infinite.
- * @throws NotANumberException if any of the probabilities are NaN.
- * @throws MathArithmeticException all of the probabilities are 0.
- */
- public EnumeratedRealDistribution(final RandomGenerator rng,
- final double[] singletons, final double[] probabilities)
- throws DimensionMismatchException, NotPositiveException, MathArithmeticException,
- NotFiniteNumberException, NotANumberException {
- super(rng);
- if (singletons.length != probabilities.length) {
- throw new DimensionMismatchException(probabilities.length, singletons.length);
- }
-
- List<Pair<Double, Double>> samples = new ArrayList<Pair<Double, Double>>(singletons.length);
-
- for (int i = 0; i < singletons.length; i++) {
- samples.add(new Pair<Double, Double>(singletons[i], probabilities[i]));
- }
-
- innerDistribution = new EnumeratedDistribution<Double>(rng, samples);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public double probability(final double x) {
- return innerDistribution.probability(x);
- }
-
- /**
- * For a random variable {@code X} whose values are distributed according to
- * this distribution, this method returns {@code P(X = x)}. In other words,
- * this method represents the probability mass function (PMF) for the
- * distribution.
- *
- * @param x the point at which the PMF is evaluated
- * @return the value of the probability mass function at point {@code x}
- */
- public double density(final double x) {
- return probability(x);
- }
-
- /**
- * {@inheritDoc}
- */
- public double cumulativeProbability(final double x) {
- double probability = 0;
-
- for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
- if (sample.getKey() <= x) {
- probability += sample.getValue();
- }
- }
-
- return probability;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public double inverseCumulativeProbability(final double p) throws OutOfRangeException {
- if (p < 0.0 || p > 1.0) {
- throw new OutOfRangeException(p, 0, 1);
- }
-
- double probability = 0;
- double x = getSupportLowerBound();
- for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
- if (sample.getValue() == 0.0) {
- continue;
- }
-
- probability += sample.getValue();
- x = sample.getKey();
-
- if (probability >= p) {
- break;
- }
- }
-
- return x;
- }
-
- /**
- * {@inheritDoc}
- *
- * @return {@code sum(singletons[i] * probabilities[i])}
- */
- public double getNumericalMean() {
- double mean = 0;
-
- for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
- mean += sample.getValue() * sample.getKey();
- }
-
- return mean;
- }
-
- /**
- * {@inheritDoc}
- *
- * @return {@code sum((singletons[i] - mean) ^ 2 * probabilities[i])}
- */
- public double getNumericalVariance() {
- double mean = 0;
- double meanOfSquares = 0;
-
- for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
- mean += sample.getValue() * sample.getKey();
- meanOfSquares += sample.getValue() * sample.getKey() * sample.getKey();
- }
-
- return meanOfSquares - mean * mean;
- }
-
- /**
- * {@inheritDoc}
- *
- * Returns the lowest value with non-zero probability.
- *
- * @return the lowest value with non-zero probability.
- */
- public double getSupportLowerBound() {
- double min = Double.POSITIVE_INFINITY;
- for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
- if (sample.getKey() < min && sample.getValue() > 0) {
- min = sample.getKey();
- }
- }
-
- return min;
- }
-
- /**
- * {@inheritDoc}
- *
- * Returns the highest value with non-zero probability.
- *
- * @return the highest value with non-zero probability.
- */
- public double getSupportUpperBound() {
- double max = Double.NEGATIVE_INFINITY;
- for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
- if (sample.getKey() > max && sample.getValue() > 0) {
- max = sample.getKey();
- }
- }
-
- return max;
- }
-
- /**
- * {@inheritDoc}
- *
- * The support of this distribution includes the lower bound.
- *
- * @return {@code true}
- */
- public boolean isSupportLowerBoundInclusive() {
- return true;
- }
-
- /**
- * {@inheritDoc}
- *
- * The support of this distribution includes the upper bound.
- *
- * @return {@code true}
- */
- public boolean isSupportUpperBoundInclusive() {
- return true;
- }
-
- /**
- * {@inheritDoc}
- *
- * The support of this distribution is connected.
- *
- * @return {@code true}
- */
- public boolean isSupportConnected() {
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public double sample() {
- return innerDistribution.sample();
- }
-}