Removed deprecated code in implementations of "IntegerDistribution".

Added "final" keyword.
Added "sample" methods to "IntegerDistribution" and "ContinuousDistribution"
interfaces.
Cleaned up Javadoc.


git-svn-id: https://svn.apache.org/repos/asf/commons/proper/math/trunk@1003512 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Gilles Sadowski 2010-10-01 12:46:16 +00:00
parent 5321415bc5
commit de001e7bcf
26 changed files with 564 additions and 765 deletions

View File

@ -20,7 +20,9 @@ import java.io.Serializable;
import org.apache.commons.math.FunctionEvaluationException; import org.apache.commons.math.FunctionEvaluationException;
import org.apache.commons.math.MathException; import org.apache.commons.math.MathException;
import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.exception.NotStrictlyPositiveException;
import org.apache.commons.math.exception.NumberIsTooSmallException;
import org.apache.commons.math.exception.OutOfRangeException;
import org.apache.commons.math.exception.util.LocalizedFormats; import org.apache.commons.math.exception.util.LocalizedFormats;
import org.apache.commons.math.random.RandomDataImpl; import org.apache.commons.math.random.RandomDataImpl;
import org.apache.commons.math.util.FastMath; import org.apache.commons.math.util.FastMath;
@ -35,12 +37,10 @@ import org.apache.commons.math.util.FastMath;
*/ */
public abstract class AbstractIntegerDistribution extends AbstractDistribution public abstract class AbstractIntegerDistribution extends AbstractDistribution
implements IntegerDistribution, Serializable { implements IntegerDistribution, Serializable {
/** Serializable version identifier */ /** Serializable version identifier */
private static final long serialVersionUID = -1146319659338487221L; private static final long serialVersionUID = -1146319659338487221L;
/** /**
* RandomData instance used to generate samples from the distribution * RandomData instance used to generate samples from the distribution.
* @since 2.2 * @since 2.2
*/ */
protected final RandomDataImpl randomData = new RandomDataImpl(); protected final RandomDataImpl randomData = new RandomDataImpl();
@ -48,22 +48,19 @@ public abstract class AbstractIntegerDistribution extends AbstractDistribution
/** /**
* Default constructor. * Default constructor.
*/ */
protected AbstractIntegerDistribution() { protected AbstractIntegerDistribution() {}
super();
}
/** /**
* For a random variable X whose values are distributed according * For a random variable {@code X} whose values are distributed according
* to this distribution, this method returns P(X &le; x). In other words, * to this distribution, this method returns {@code P(X < x)}. In other
* this method represents the (cumulative) distribution function, or * words, this method represents the (cumulative) distribution function,
* CDF, for this distribution. * or CDF, for this distribution.
* <p> * If {@code x} does not represent an integer value, the CDF is
* If <code>x</code> does not represent an integer value, the CDF is * evaluated at the greatest integer less than {@code x}.
* evaluated at the greatest integer less than x.
* *
* @param x the value at which the distribution function is evaluated. * @param x Value at which the distribution function is evaluated.
* @return cumulative probability that a random variable with this * @return the cumulative probability that a random variable with this
* distribution takes a value less than or equal to <code>x</code> * distribution takes a value less than or equal to {@code x}.
* @throws MathException if the cumulative probability can not be * @throws MathException if the cumulative probability can not be
* computed due to convergence or other numerical errors. * computed due to convergence or other numerical errors.
*/ */
@ -72,24 +69,25 @@ public abstract class AbstractIntegerDistribution extends AbstractDistribution
} }
/** /**
* For a random variable X whose values are distributed according * For a random variable {@code X} whose values are distributed
* to this distribution, this method returns P(x0 &le; X &le; x1). * according to this distribution, this method returns
* {@code P(x0 < X < x1)}.
* *
* @param x0 the (inclusive) lower bound * @param x0 Inclusive lower bound.
* @param x1 the (inclusive) upper bound * @param x1 Inclusive upper bound.
* @return the probability that a random variable with this distribution * @return the probability that a random variable with this distribution
* will take a value between <code>x0</code> and <code>x1</code>, * will take a value between {@code x0} and {@code x1},
* including the endpoints. * including the endpoints.
* @throws MathException if the cumulative probability can not be * @throws MathException if the cumulative probability can not be
* computed due to convergence or other numerical errors. * computed due to convergence or other numerical errors.
* @throws IllegalArgumentException if <code>x0 > x1</code> * @throws NumberIsTooSmallException if {@code x1 > x0}.
*/ */
@Override @Override
public double cumulativeProbability(double x0, double x1) public double cumulativeProbability(double x0, double x1)
throws MathException { throws MathException {
if (x0 > x1) { if (x1 < x0) {
throw MathRuntimeException.createIllegalArgumentException( throw new NumberIsTooSmallException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT,
LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT, x0, x1); x0, x1, true);
} }
if (FastMath.floor(x0) < x0) { if (FastMath.floor(x0) < x0) {
return cumulativeProbability(((int) FastMath.floor(x0)) + 1, return cumulativeProbability(((int) FastMath.floor(x0)) + 1,
@ -101,27 +99,27 @@ public abstract class AbstractIntegerDistribution extends AbstractDistribution
} }
/** /**
* For a random variable X whose values are distributed according * For a random variable {@code X} whose values are distributed according
* to this distribution, this method returns P(X &le; x). In other words, * to this distribution, this method returns {@code P(X < x)}. In other
* this method represents the probability distribution function, or PDF, * words, this method represents the probability distribution function,
* for this distribution. * or PDF, for this distribution.
* *
* @param x the value at which the PDF is evaluated. * @param x Value at which the PDF is evaluated.
* @return PDF for this distribution. * @return PDF for this distribution.
* @throws MathException if the cumulative probability can not be * @throws MathException if the cumulative probability can not be
* computed due to convergence or other numerical errors. * computed due to convergence or other numerical errors.
*/ */
public abstract double cumulativeProbability(int x) throws MathException; public abstract double cumulativeProbability(int x) throws MathException;
/** /**
* For a random variable X whose values are distributed according * For a random variable {@code X} whose values are distributed according
* to this distribution, this method returns P(X = x). In other words, this * to this distribution, this method returns {@code P(X = x)}. In other
* method represents the probability mass function, or PMF, for the distribution. * words, this method represents the probability mass function, or PMF,
* <p> * for the distribution.
* If <code>x</code> does not represent an integer value, 0 is returned. * If {@code x} does not represent an integer value, 0 is returned.
* *
* @param x the value at which the probability density function is evaluated * @param x Value at which the probability density function is evaluated.
* @return the value of the probability density function at x * @return the value of the probability density function at {@code x}.
*/ */
public double probability(double x) { public double probability(double x) {
double fl = FastMath.floor(x); double fl = FastMath.floor(x);
@ -133,39 +131,38 @@ public abstract class AbstractIntegerDistribution extends AbstractDistribution
} }
/** /**
* For a random variable X whose values are distributed according * For a random variable {@code X} whose values are distributed according
* to this distribution, this method returns P(x0 &le; X &le; x1). * to this distribution, this method returns {@code P(x0 < X < x1)}.
* *
* @param x0 the inclusive, lower bound * @param x0 Inclusive lower bound.
* @param x1 the inclusive, upper bound * @param x1 Inclusive upper bound.
* @return the cumulative probability. * @return the cumulative probability.
* @throws MathException if the cumulative probability can not be * @throws MathException if the cumulative probability can not be
* computed due to convergence or other numerical errors. * computed due to convergence or other numerical errors.
* @throws IllegalArgumentException if x0 > x1 * @throws NumberIsTooSmallException {@code if x0 > x1}.
*/ */
public double cumulativeProbability(int x0, int x1) throws MathException { public double cumulativeProbability(int x0, int x1) throws MathException {
if (x0 > x1) { if (x1 < x0) {
throw MathRuntimeException.createIllegalArgumentException( throw new NumberIsTooSmallException(LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT,
LocalizedFormats.LOWER_ENDPOINT_ABOVE_UPPER_ENDPOINT, x0, x1); x0, x1, true);
} }
return cumulativeProbability(x1) - cumulativeProbability(x0 - 1); return cumulativeProbability(x1) - cumulativeProbability(x0 - 1);
} }
/** /**
* For a random variable X whose values are distributed according * For a random variable {@code X} whose values are distributed according
* to this distribution, this method returns the largest x, such * to this distribution, this method returns the largest {@code x}, such
* that P(X &le; x) &le; <code>p</code>. * that {@code P(X < x) < p}.
* *
* @param p the desired probability * @param p Desired probability.
* @return the largest x such that P(X &le; x) <= p * @return the largest {@code x} such that {@code P(X < x) <= p}.
* @throws MathException if the inverse cumulative probability can not be * @throws MathException if the inverse cumulative probability can not be
* computed due to convergence or other numerical errors. * computed due to convergence or other numerical errors.
* @throws IllegalArgumentException if p < 0 or p > 1 * @throws OutOfRangeException if {@code p < 0} or {@code p > 1}.
*/ */
public int inverseCumulativeProbability(final double p) throws MathException{ public int inverseCumulativeProbability(final double p) throws MathException{
if (p < 0.0 || p > 1.0) { if (p < 0 || p > 1) {
throw MathRuntimeException.createIllegalArgumentException( throw new OutOfRangeException(p, 0, 1);
LocalizedFormats.OUT_OF_RANGE_SIMPLE, p, 0.0, 1.0);
} }
// by default, do simple bisection. // by default, do simple bisection.
@ -210,10 +207,7 @@ public abstract class AbstractIntegerDistribution extends AbstractDistribution
} }
/** /**
* Reseeds the random generator used to generate samples. * {@inheritDoc}
*
* @param seed the new seed
* @since 2.2
*/ */
public void reseedRandomGenerator(long seed) { public void reseedRandomGenerator(long seed) {
randomData.reSeed(seed); randomData.reSeed(seed);
@ -222,29 +216,33 @@ public abstract class AbstractIntegerDistribution extends AbstractDistribution
/** /**
* Generates a random value sampled from this distribution. The default * Generates a random value sampled from this distribution. The default
* implementation uses the * implementation uses the
* <a href="http://en.wikipedia.org/wiki/Inverse_transform_sampling"> inversion method.</a> * <a href="http://en.wikipedia.org/wiki/Inverse_transform_sampling">
* inversion method.
* </a>
* *
* @return random value * @return a random value.
* @since 2.2 * @since 2.2
* @throws MathException if an error occurs generating the random value * @throws MathException if an error occurs generating the random value.
*/ */
public int sample() throws MathException { public int sample() throws MathException {
return randomData.nextInversionDeviate(this); return randomData.nextInversionDeviate(this);
} }
/** /**
* Generates a random sample from the distribution. The default implementation * Generates a random sample from the distribution. The default
* generates the sample by calling {@link #sample()} in a loop. * implementation generates the sample by calling {@link #sample()}
* in a loop.
* *
* @param sampleSize number of random values to generate * @param sampleSize number of random values to generate.
* @since 2.2 * @since 2.2
* @return an array representing the random sample * @return an array representing the random sample.
* @throws MathException if an error occurs generating the sample * @throws MathException if an error occurs generating the sample.
* @throws IllegalArgumentException if sampleSize is not positive * @throws NotStrictlyPositiveException if {@code sampleSize <= 0}.
*/ */
public int[] sample(int sampleSize) throws MathException { public int[] sample(int sampleSize) throws MathException {
if (sampleSize <= 0) { if (sampleSize <= 0) {
MathRuntimeException.createIllegalArgumentException(LocalizedFormats.NOT_POSITIVE_SAMPLE_SIZE, sampleSize); throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES,
sampleSize);
} }
int[] out = new int[sampleSize]; int[] out = new int[sampleSize];
for (int i = 0; i < sampleSize; i++) { for (int i = 0; i < sampleSize; i++) {
@ -254,16 +252,21 @@ public abstract class AbstractIntegerDistribution extends AbstractDistribution
} }
/** /**
* Computes the cumulative probability function and checks for NaN values returned. * Computes the cumulative probability function and checks for NaN
* Throws MathException if the value is NaN. Wraps and rethrows any MathException encountered * values returned.
* evaluating the cumulative probability function in a FunctionEvaluationException. Throws * Throws MathException if the value is NaN. Wraps and rethrows any
* FunctionEvaluationException of the cumulative probability function returns NaN. * MathException encountered evaluating the cumulative probability
* function in a FunctionEvaluationException.
* Throws FunctionEvaluationException of the cumulative probability
* function returns NaN.
* *
* @param argument input value * @param argument Input value.
* @return cumulative probability * @return the cumulative probability.
* @throws FunctionEvaluationException if a MathException occurs computing the cumulative probability * @throws FunctionEvaluationException if a MathException occurs
* computing the cumulative probability.
*/ */
private double checkedCumulativeProbability(int argument) throws FunctionEvaluationException { private double checkedCumulativeProbability(int argument)
throws FunctionEvaluationException {
double result = Double.NaN; double result = Double.NaN;
try { try {
result = cumulativeProbability(argument); result = cumulativeProbability(argument);
@ -278,24 +281,22 @@ public abstract class AbstractIntegerDistribution extends AbstractDistribution
} }
/** /**
* Access the domain value lower bound, based on <code>p</code>, used to * Access the domain value lower bound, based on {@code p}, used to
* bracket a PDF root. This method is used by * bracket a PDF root. This method is used by
* {@link #inverseCumulativeProbability(double)} to find critical values. * {@link #inverseCumulativeProbability(double)} to find critical values.
* *
* @param p the desired probability for the critical value * @param p Desired probability for the critical value
* @return domain value lower bound, i.e. * @return the domain value lower bound, i.e. {@code P(X < 'lower bound') < p}.
* P(X &lt; <i>lower bound</i>) &lt; <code>p</code>
*/ */
protected abstract int getDomainLowerBound(double p); protected abstract int getDomainLowerBound(double p);
/** /**
* Access the domain value upper bound, based on <code>p</code>, used to * Access the domain value upper bound, based on {@code p}, used to
* bracket a PDF root. This method is used by * bracket a PDF root. This method is used by
* {@link #inverseCumulativeProbability(double)} to find critical values. * {@link #inverseCumulativeProbability(double)} to find critical values.
* *
* @param p the desired probability for the critical value * @param p Desired probability for the critical value.
* @return domain value upper bound, i.e. * @return the domain value upper bound, i.e. {@code P(X < 'upper bound') > p}.
* P(X &lt; <i>upper bound</i>) &gt; <code>p</code>
*/ */
protected abstract int getDomainUpperBound(double p); protected abstract int getDomainUpperBound(double p);
} }

View File

@ -37,28 +37,22 @@ import org.apache.commons.math.util.FastMath;
*/ */
public class BetaDistributionImpl public class BetaDistributionImpl
extends AbstractContinuousDistribution implements BetaDistribution { extends AbstractContinuousDistribution implements BetaDistribution {
/** /**
* Default inverse cumulative probability accurac * Default inverse cumulative probability accuracy.
* @since 2.1 * @since 2.1
*/ */
public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9; public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
/** Serializable version identifier. */ /** Serializable version identifier. */
private static final long serialVersionUID = -1221965979403477668L; private static final long serialVersionUID = -1221965979403477668L;
/** First shape parameter. */ /** First shape parameter. */
private double alpha; private final double alpha;
/** Second shape parameter. */ /** Second shape parameter. */
private double beta; private final double beta;
/** Normalizing factor used in density computations. /** Normalizing factor used in density computations.
* updated whenever alpha or beta are changed. * updated whenever alpha or beta are changed.
*/ */
private double z; private double z;
/** Inverse cumulative probability accuracy. */
/** Inverse cumulative probability accuracy */
private final double solverAbsoluteAccuracy; private final double solverAbsoluteAccuracy;
/** /**

View File

@ -32,29 +32,15 @@ package org.apache.commons.math.distribution;
public interface BinomialDistribution extends IntegerDistribution { public interface BinomialDistribution extends IntegerDistribution {
/** /**
* Access the number of trials for this distribution. * Access the number of trials for this distribution.
*
* @return the number of trials. * @return the number of trials.
*/ */
int getNumberOfTrials(); int getNumberOfTrials();
/** /**
* Access the probability of success for this distribution. * Access the probability of success for this distribution.
*
* @return the probability of success. * @return the probability of success.
*/ */
double getProbabilityOfSuccess(); double getProbabilityOfSuccess();
/**
* Change the number of trials for this distribution.
* @param trials the new number of trials.
* @deprecated as of v2.1
*/
@Deprecated
void setNumberOfTrials(int trials);
/**
* Change the probability of success for this distribution.
* @param p the new probability of success.
* @deprecated as of v2.1
*/
@Deprecated
void setProbabilityOfSuccess(double p);
} }

View File

@ -19,7 +19,8 @@ package org.apache.commons.math.distribution;
import java.io.Serializable; import java.io.Serializable;
import org.apache.commons.math.MathException; import org.apache.commons.math.MathException;
import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.exception.OutOfRangeException;
import org.apache.commons.math.exception.NotPositiveException;
import org.apache.commons.math.exception.util.LocalizedFormats; import org.apache.commons.math.exception.util.LocalizedFormats;
import org.apache.commons.math.special.Beta; import org.apache.commons.math.special.Beta;
import org.apache.commons.math.util.FastMath; import org.apache.commons.math.util.FastMath;
@ -31,108 +32,55 @@ import org.apache.commons.math.util.FastMath;
*/ */
public class BinomialDistributionImpl extends AbstractIntegerDistribution public class BinomialDistributionImpl extends AbstractIntegerDistribution
implements BinomialDistribution, Serializable { implements BinomialDistribution, Serializable {
/** Serializable version identifier. */
/** Serializable version identifier */
private static final long serialVersionUID = 6751309484392813623L; private static final long serialVersionUID = 6751309484392813623L;
/** The number of trials. */ /** The number of trials. */
private int numberOfTrials; private final int numberOfTrials;
/** The probability of success. */ /** The probability of success. */
private double probabilityOfSuccess; private final double probabilityOfSuccess;
/** /**
* Create a binomial distribution with the given number of trials and * Create a binomial distribution with the given number of trials and
* probability of success. * probability of success.
* *
* @param trials the number of trials. * @param trials Number of trials.
* @param p the probability of success. * @param p Probability of success.
* @throws NotPositiveException if {@code trials < 0}.
* @throws OutOfRangeException if {@code p < 0} or {@code p > 1}.
*/ */
public BinomialDistributionImpl(int trials, double p) { public BinomialDistributionImpl(int trials, double p) {
super(); if (trials < 0) {
setNumberOfTrialsInternal(trials); throw new NotPositiveException(LocalizedFormats.NUMBER_OF_TRIALS,
setProbabilityOfSuccessInternal(p); trials);
}
if (p < 0 || p > 1) {
throw new OutOfRangeException(p, 0, 1);
}
probabilityOfSuccess = p;
numberOfTrials = trials;
} }
/** /**
* Access the number of trials for this distribution. * {@inheritDoc}
*
* @return the number of trials.
*/ */
public int getNumberOfTrials() { public int getNumberOfTrials() {
return numberOfTrials; return numberOfTrials;
} }
/** /**
* Access the probability of success for this distribution. * {@inheritDoc}
*
* @return the probability of success.
*/ */
public double getProbabilityOfSuccess() { public double getProbabilityOfSuccess() {
return probabilityOfSuccess; return probabilityOfSuccess;
} }
/** /**
* Change the number of trials for this distribution. * Access the domain value lower bound, based on {@code p}, used to
*
* @param trials the new number of trials.
* @throws IllegalArgumentException if <code>trials</code> is not a valid
* number of trials.
* @deprecated as of 2.1 (class will become immutable in 3.0)
*/
@Deprecated
public void setNumberOfTrials(int trials) {
setNumberOfTrialsInternal(trials);
}
/**
* Change the number of trials for this distribution.
*
* @param trials the new number of trials.
* @throws IllegalArgumentException if <code>trials</code> is not a valid
* number of trials.
*/
private void setNumberOfTrialsInternal(int trials) {
if (trials < 0) {
throw MathRuntimeException.createIllegalArgumentException(
LocalizedFormats.NEGATIVE_NUMBER_OF_TRIALS, trials);
}
numberOfTrials = trials;
}
/**
* Change the probability of success for this distribution.
*
* @param p the new probability of success.
* @throws IllegalArgumentException if <code>p</code> is not a valid
* probability.
* @deprecated as of 2.1 (class will become immutable in 3.0)
*/
@Deprecated
public void setProbabilityOfSuccess(double p) {
setProbabilityOfSuccessInternal(p);
}
/**
* Change the probability of success for this distribution.
*
* @param p the new probability of success.
* @throws IllegalArgumentException if <code>p</code> is not a valid
* probability.
*/
private void setProbabilityOfSuccessInternal(double p) {
if (p < 0.0 || p > 1.0) {
throw MathRuntimeException.createIllegalArgumentException(
LocalizedFormats.OUT_OF_RANGE_SIMPLE, p, 0.0, 1.0);
}
probabilityOfSuccess = p;
}
/**
* Access the domain value lower bound, based on <code>p</code>, used to
* bracket a PDF root. * bracket a PDF root.
* *
* @param p the desired probability for the critical value * @param p Desired probability for the critical value.
* @return domain value lower bound, i.e. P(X &lt; <i>lower bound</i>) &lt; * @return the domain value lower bound, i.e. {@code P(X < 'lower bound') < p}.
* <code>p</code>
*/ */
@Override @Override
protected int getDomainLowerBound(double p) { protected int getDomainLowerBound(double p) {
@ -140,12 +88,11 @@ public class BinomialDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* Access the domain value upper bound, based on <code>p</code>, used to * Access the domain value upper bound, based on {@code p}, used to
* bracket a PDF root. * bracket a PDF root.
* *
* @param p the desired probability for the critical value * @param p Desired probability for the critical value
* @return domain value upper bound, i.e. P(X &lt; <i>upper bound</i>) &gt; * @return the domain value upper bound, i.e. {@code P(X < 'upper bound') > p}.
* <code>p</code>
*/ */
@Override @Override
protected int getDomainUpperBound(double p) { protected int getDomainUpperBound(double p) {
@ -153,12 +100,12 @@ public class BinomialDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* For this distribution, X, this method returns P(X &le; x). * For this distribution, {@code X}, this method returns {@code P(X < x)}.
* *
* @param x the value at which the PDF is evaluated. * @param x Value at which the PDF is evaluated.
* @return PDF for this distribution. * @return PDF for this distribution.
* @throws MathException if the cumulative probability can not be computed * @throws MathException if the cumulative probability can not be computed
* due to convergence or other numerical errors. * due to convergence or other numerical errors.
*/ */
@Override @Override
public double cumulativeProbability(int x) throws MathException { public double cumulativeProbability(int x) throws MathException {
@ -175,9 +122,9 @@ public class BinomialDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* For this distribution, X, this method returns P(X = x). * For this distribution, {@code X}, this method returns {@code P(X = x)}.
* *
* @param x the value at which the PMF is evaluated. * @param x Value at which the PMF is evaluated.
* @return PMF for this distribution. * @return PMF for this distribution.
*/ */
public double probability(int x) { public double probability(int x) {
@ -193,18 +140,15 @@ public class BinomialDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* For this distribution, X, this method returns the largest x, such that * For this distribution, {@code X}, this method returns the largest
* P(X &le; x) &le; <code>p</code>. * {@code x}, such that {@code P(X < x) p}.
* <p> * It will return -1 when p = 0 and {@code Integer.MAX_VALUE} when p = 1.
* Returns <code>-1</code> for p=0 and <code>Integer.MAX_VALUE</code> for
* p=1.
* </p>
* *
* @param p the desired probability * @param p Desired probability.
* @return the largest x such that P(X &le; x) <= p * @return the largest {@code x} such that {@code P(X < x) <= p}.
* @throws MathException if the inverse cumulative probability can not be * @throws MathException if the inverse cumulative probability can not be
* computed due to convergence or other numerical errors. * computed due to convergence or other numerical errors.
* @throws IllegalArgumentException if p < 0 or p > 1 * @throws OutOfRangeException if {@code p < 0} or {@code p > 1}.
*/ */
@Override @Override
public int inverseCumulativeProbability(final double p) public int inverseCumulativeProbability(final double p)

View File

@ -32,18 +32,18 @@ import org.apache.commons.math.util.FastMath;
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
public class CauchyDistributionImpl extends AbstractContinuousDistribution public class CauchyDistributionImpl extends AbstractContinuousDistribution
implements CauchyDistribution, Serializable { implements CauchyDistribution, Serializable {
/** /**
* Default inverse cumulative probability accuracy * Default inverse cumulative probability accuracy.
* @since 2.1 * @since 2.1
*/ */
public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9; public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
/** Serializable version identifier */ /** Serializable version identifier */
private static final long serialVersionUID = 8589540077390120676L; private static final long serialVersionUID = 8589540077390120676L;
/** The median of this distribution. */ /** The median of this distribution. */
private double median = 0; private final double median;
/** The scale of this distribution. */ /** The scale of this distribution. */
private double scale = 1; private final double scale;
/** Inverse cumulative probability accuracy */ /** Inverse cumulative probability accuracy */
private final double solverAbsoluteAccuracy; private final double solverAbsoluteAccuracy;

View File

@ -36,7 +36,7 @@ public class ChiSquaredDistributionImpl
/** Serializable version identifier */ /** Serializable version identifier */
private static final long serialVersionUID = -8352658048349159782L; private static final long serialVersionUID = -8352658048349159782L;
/** Internal Gamma distribution. */ /** Internal Gamma distribution. */
private GammaDistribution gamma; private final GammaDistribution gamma;
/** Inverse cumulative probability accuracy */ /** Inverse cumulative probability accuracy */
private final double solverAbsoluteAccuracy; private final double solverAbsoluteAccuracy;

View File

@ -42,4 +42,33 @@ public interface ContinuousDistribution extends Distribution {
* @return the pdf at point {@code x}. * @return the pdf at point {@code x}.
*/ */
double density(double x); double density(double x);
/**
* Reseed the random generator used to generate samples.
*
* @param seed New seed.
* @since 3.0
*/
void reseedRandomGenerator(long seed);
/**
* Generate a random value sampled from this distribution.
*
* @return a random value.
* @throws MathException if an error occurs generating the random value.
* @since 3.0
*/
double sample() throws MathException;
/**
* Generate a random sample from the distribution.
*
* @param sampleSize number of random values to generate.
* @return an array representing the random sample.
* @throws MathException if an error occurs generating the sample.
* @throws org.apache.commons.math.exception.NotStrictlyPositiveException
* if {@code sampleSize} is not positive.
* @since 3.0
*/
double[] sample(int sampleSize) throws MathException;
} }

View File

@ -32,15 +32,15 @@ import org.apache.commons.math.util.FastMath;
public class ExponentialDistributionImpl extends AbstractContinuousDistribution public class ExponentialDistributionImpl extends AbstractContinuousDistribution
implements ExponentialDistribution, Serializable { implements ExponentialDistribution, Serializable {
/** /**
* Default inverse cumulative probability accuracy * Default inverse cumulative probability accuracy.
* @since 2.1 * @since 2.1
*/ */
public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9; public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
/** Serializable version identifier */ /** Serializable version identifier */
private static final long serialVersionUID = 2401296428283614780L; private static final long serialVersionUID = 2401296428283614780L;
/** The mean of this distribution. */ /** The mean of this distribution. */
private double mean; private final double mean;
/** Inverse cumulative probability accuracy */ /** Inverse cumulative probability accuracy. */
private final double solverAbsoluteAccuracy; private final double solverAbsoluteAccuracy;
/** /**

View File

@ -35,17 +35,17 @@ public class FDistributionImpl
extends AbstractContinuousDistribution extends AbstractContinuousDistribution
implements FDistribution, Serializable { implements FDistribution, Serializable {
/** /**
* Default inverse cumulative probability accuracy * Default inverse cumulative probability accuracy.
* @since 2.1 * @since 2.1
*/ */
public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9; public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
/** Serializable version identifier */ /** Serializable version identifier. */
private static final long serialVersionUID = -8516354193418641566L; private static final long serialVersionUID = -8516354193418641566L;
/** The numerator degrees of freedom*/ /** The numerator degrees of freedom. */
private double numeratorDegreesOfFreedom; private final double numeratorDegreesOfFreedom;
/** The numerator degrees of freedom*/ /** The numerator degrees of freedom. */
private double denominatorDegreesOfFreedom; private final double denominatorDegreesOfFreedom;
/** Inverse cumulative probability accuracy */ /** Inverse cumulative probability accuracy. */
private final double solverAbsoluteAccuracy; private final double solverAbsoluteAccuracy;
/** /**

View File

@ -31,23 +31,18 @@ import org.apache.commons.math.util.FastMath;
*/ */
public class GammaDistributionImpl extends AbstractContinuousDistribution public class GammaDistributionImpl extends AbstractContinuousDistribution
implements GammaDistribution, Serializable { implements GammaDistribution, Serializable {
/** /**
* Default inverse cumulative probability accuracy * Default inverse cumulative probability accuracy.
* @since 2.1 * @since 2.1
*/ */
public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9; public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
/** Serializable version identifier. */
/** Serializable version identifier */
private static final long serialVersionUID = -3239549463135430361L; private static final long serialVersionUID = -3239549463135430361L;
/** The shape parameter. */ /** The shape parameter. */
private double alpha; private final double alpha;
/** The scale parameter. */ /** The scale parameter. */
private double beta; private final double beta;
/** Inverse cumulative probability accuracy. */
/** Inverse cumulative probability accuracy */
private final double solverAbsoluteAccuracy; private final double solverAbsoluteAccuracy;
/** /**

View File

@ -31,46 +31,24 @@ package org.apache.commons.math.distribution;
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
public interface HypergeometricDistribution extends IntegerDistribution { public interface HypergeometricDistribution extends IntegerDistribution {
/** /**
* Access the number of successes. * Access the number of successes.
*
* @return the number of successes. * @return the number of successes.
*/ */
int getNumberOfSuccesses(); int getNumberOfSuccesses();
/** /**
* Access the population size. * Access the population size.
*
* @return the population size. * @return the population size.
*/ */
int getPopulationSize(); int getPopulationSize();
/** /**
* Access the sample size. * Access the sample size.
*
* @return the sample size. * @return the sample size.
*/ */
int getSampleSize(); int getSampleSize();
/**
* Modify the number of successes.
* @param num the new number of successes.
* @deprecated as of v2.1
*/
@Deprecated
void setNumberOfSuccesses(int num);
/**
* Modify the population size.
* @param size the new population size.
* @deprecated as of v2.1
*/
@Deprecated
void setPopulationSize(int size);
/**
* Modify the sample size.
* @param size the new sample size.
* @deprecated as of v2.1
*/
@Deprecated
void setSampleSize(int size);
} }

View File

@ -19,7 +19,9 @@ package org.apache.commons.math.distribution;
import java.io.Serializable; import java.io.Serializable;
import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.exception.NotPositiveException;
import org.apache.commons.math.exception.NotStrictlyPositiveException;
import org.apache.commons.math.exception.NumberIsTooLargeException;
import org.apache.commons.math.exception.util.LocalizedFormats; import org.apache.commons.math.exception.util.LocalizedFormats;
import org.apache.commons.math.util.MathUtils; import org.apache.commons.math.util.MathUtils;
import org.apache.commons.math.util.FastMath; import org.apache.commons.math.util.FastMath;
@ -30,53 +32,64 @@ import org.apache.commons.math.util.FastMath;
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
public class HypergeometricDistributionImpl extends AbstractIntegerDistribution public class HypergeometricDistributionImpl extends AbstractIntegerDistribution
implements HypergeometricDistribution, Serializable { implements HypergeometricDistribution, Serializable {
/** Serializable version identifier. */
/** Serializable version identifier */
private static final long serialVersionUID = -436928820673516179L; private static final long serialVersionUID = -436928820673516179L;
/** The number of successes in the population. */ /** The number of successes in the population. */
private int numberOfSuccesses; private final int numberOfSuccesses;
/** The population size. */ /** The population size. */
private int populationSize; private final int populationSize;
/** The sample size. */ /** The sample size. */
private int sampleSize; private final int sampleSize;
/** /**
* Construct a new hypergeometric distribution with the given the population * Construct a new hypergeometric distribution with the given the
* size, the number of successes in the population, and the sample size. * population size, the number of successes in the population, and
* the sample size.
* *
* @param populationSize the population size. * @param populationSize Population size.
* @param numberOfSuccesses number of successes in the population. * @param numberOfSuccesses Number of successes in the population.
* @param sampleSize the sample size. * @param sampleSize Sample size.
* @throws NotPositiveException if {@code numberOfSuccesses < 0}.
* @throws NotStrictlyPositiveException if {@code populationSize <= 0}.
* @throws NotPositiveException if {@code populationSize < 0}.
* @throws NumberIsTooLargeException if {@code numberOfSuccesses > populationSize}.
* @throws NumberIsTooLargeException if {@code sampleSize > populationSize}.
*/ */
public HypergeometricDistributionImpl(int populationSize, public HypergeometricDistributionImpl(int populationSize,
int numberOfSuccesses, int sampleSize) { int numberOfSuccesses,
super(); int sampleSize) {
if (numberOfSuccesses > populationSize) { if (populationSize <= 0) {
throw MathRuntimeException throw new NotStrictlyPositiveException(LocalizedFormats.POPULATION_SIZE,
.createIllegalArgumentException( populationSize);
LocalizedFormats.NUMBER_OF_SUCCESS_LARGER_THAN_POPULATION_SIZE,
numberOfSuccesses, populationSize);
} }
if (sampleSize > populationSize) { if (numberOfSuccesses < 0) {
throw MathRuntimeException throw new NotPositiveException(LocalizedFormats.NUMBER_OF_SUCCESSES,
.createIllegalArgumentException( numberOfSuccesses);
LocalizedFormats.SAMPLE_SIZE_LARGER_THAN_POPULATION_SIZE, }
sampleSize, populationSize); if (sampleSize < 0) {
throw new NotPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES,
sampleSize);
} }
setPopulationSizeInternal(populationSize); if (numberOfSuccesses > populationSize) {
setSampleSizeInternal(sampleSize); throw new NumberIsTooLargeException(LocalizedFormats.NUMBER_OF_SUCCESS_LARGER_THAN_POPULATION_SIZE,
setNumberOfSuccessesInternal(numberOfSuccesses); numberOfSuccesses, populationSize, true);
}
if (sampleSize > populationSize) {
throw new NumberIsTooLargeException(LocalizedFormats.SAMPLE_SIZE_LARGER_THAN_POPULATION_SIZE,
sampleSize, populationSize, true);
}
this.numberOfSuccesses = numberOfSuccesses;
this.populationSize = populationSize;
this.sampleSize = sampleSize;
} }
/** /**
* For this distribution, X, this method returns P(X &le; x). * For this distribution, {@code X}, this method returns {@code P(X < x)}.
* *
* @param x the value at which the PDF is evaluated. * @param x Value at which the PDF is evaluated.
* @return PDF for this distribution. * @return PDF for this distribution.
*/ */
@Override @Override
@ -99,23 +112,22 @@ public class HypergeometricDistributionImpl extends AbstractIntegerDistribution
/** /**
* Return the domain for the given hypergeometric distribution parameters. * Return the domain for the given hypergeometric distribution parameters.
* *
* @param n the population size. * @param n Population size.
* @param m number of successes in the population. * @param m Number of successes in the population.
* @param k the sample size. * @param k Sample size.
* @return a two element array containing the lower and upper bounds of the * @return a two element array containing the lower and upper bounds of the
* hypergeometric distribution. * hypergeometric distribution.
*/ */
private int[] getDomain(int n, int m, int k) { private int[] getDomain(int n, int m, int k) {
return new int[] { getLowerDomain(n, m, k), getUpperDomain(m, k) }; return new int[] { getLowerDomain(n, m, k), getUpperDomain(m, k) };
} }
/** /**
* Access the domain value lower bound, based on <code>p</code>, used to * Access the domain value lower bound, based on {@code p}, used to
* bracket a PDF root. * bracket a PDF root.
* *
* @param p the desired probability for the critical value * @param p Desired probability for the critical value.
* @return domain value lower bound, i.e. P(X &lt; <i>lower bound</i>) &lt; * @return the domain value lower bound, i.e. {@code P(X < 'lower bound') < p}.
* <code>p</code>
*/ */
@Override @Override
protected int getDomainLowerBound(double p) { protected int getDomainLowerBound(double p) {
@ -123,12 +135,11 @@ public class HypergeometricDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* Access the domain value upper bound, based on <code>p</code>, used to * Access the domain value upper bound, based on {@code p}, used to
* bracket a PDF root. * bracket a PDF root.
* *
* @param p the desired probability for the critical value * @param p Desired probability for the critical value
* @return domain value upper bound, i.e. P(X &lt; <i>upper bound</i>) &gt; * @return the domain value upper bound, i.e. {@code P(X < 'upper bound') > p}.
* <code>p</code>
*/ */
@Override @Override
protected int getDomainUpperBound(double p) { protected int getDomainUpperBound(double p) {
@ -139,9 +150,9 @@ public class HypergeometricDistributionImpl extends AbstractIntegerDistribution
* Return the lowest domain value for the given hypergeometric distribution * Return the lowest domain value for the given hypergeometric distribution
* parameters. * parameters.
* *
* @param n the population size. * @param n Population size.
* @param m number of successes in the population. * @param m Number of successes in the population.
* @param k the sample size. * @param k Sample size.
* @return the lowest domain value of the hypergeometric distribution. * @return the lowest domain value of the hypergeometric distribution.
*/ */
private int getLowerDomain(int n, int m, int k) { private int getLowerDomain(int n, int m, int k) {
@ -149,27 +160,21 @@ public class HypergeometricDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* Access the number of successes. * {@inheritDoc}
*
* @return the number of successes.
*/ */
public int getNumberOfSuccesses() { public int getNumberOfSuccesses() {
return numberOfSuccesses; return numberOfSuccesses;
} }
/** /**
* Access the population size. * {@inheritDoc}
*
* @return the population size.
*/ */
public int getPopulationSize() { public int getPopulationSize() {
return populationSize; return populationSize;
} }
/** /**
* Access the sample size. * {@inheritDoc}
*
* @return the sample size.
*/ */
public int getSampleSize() { public int getSampleSize() {
return sampleSize; return sampleSize;
@ -179,8 +184,8 @@ public class HypergeometricDistributionImpl extends AbstractIntegerDistribution
* Return the highest domain value for the given hypergeometric distribution * Return the highest domain value for the given hypergeometric distribution
* parameters. * parameters.
* *
* @param m number of successes in the population. * @param m Number of successes in the population.
* @param k the sample size. * @param k Sample size.
* @return the highest domain value of the hypergeometric distribution. * @return the highest domain value of the hypergeometric distribution.
*/ */
private int getUpperDomain(int m, int k) { private int getUpperDomain(int m, int k) {
@ -188,9 +193,9 @@ public class HypergeometricDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* For this distribution, X, this method returns P(X = x). * For this distribution, {@code X}, this method returns {@code P(X = x)}.
* *
* @param x the value at which the PMF is evaluated. * @param x Value at which the PMF is evaluated.
* @return PMF for this distribution. * @return PMF for this distribution.
*/ */
public double probability(int x) { public double probability(int x) {
@ -216,13 +221,13 @@ public class HypergeometricDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* For the distribution, X, defined by the given hypergeometric distribution * For this distribution, {@code X}, defined by the given hypergeometric
* parameters, this method returns P(X = x). * distribution parameters, this method returns {@code P(X = x)}.
* *
* @param x Value at which the PMF is evaluated.
* @param n the population size. * @param n the population size.
* @param m number of successes in the population. * @param m number of successes in the population.
* @param k the sample size. * @param k the sample size.
* @param x the value at which the PMF is evaluated.
* @return PMF for the distribution. * @return PMF for the distribution.
*/ */
private double probability(int n, int m, int k, int x) { private double probability(int n, int m, int k, int x) {
@ -232,85 +237,10 @@ public class HypergeometricDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* Modify the number of successes. * For this distribution, {@code X}, this method returns {@code P(X >= x)}.
* *
* @param num the new number of successes. * @param x Value at which the CDF is evaluated.
* @throws IllegalArgumentException if <code>num</code> is negative. * @return the upper tail CDF for this distribution.
* @deprecated as of 2.1 (class will become immutable in 3.0)
*/
@Deprecated
public void setNumberOfSuccesses(int num) {
setNumberOfSuccessesInternal(num);
}
/**
* Modify the number of successes.
*
* @param num the new number of successes.
* @throws IllegalArgumentException if <code>num</code> is negative.
*/
private void setNumberOfSuccessesInternal(int num) {
if (num < 0) {
throw MathRuntimeException.createIllegalArgumentException(
LocalizedFormats.NEGATIVE_NUMBER_OF_SUCCESSES, num);
}
numberOfSuccesses = num;
}
/**
* Modify the population size.
*
* @param size the new population size.
* @throws IllegalArgumentException if <code>size</code> is not positive.
* @deprecated as of 2.1 (class will become immutable in 3.0)
*/
@Deprecated
public void setPopulationSize(int size) {
setPopulationSizeInternal(size);
}
/**
* Modify the population size.
*
* @param size the new population size.
* @throws IllegalArgumentException if <code>size</code> is not positive.
*/
private void setPopulationSizeInternal(int size) {
if (size <= 0) {
throw MathRuntimeException.createIllegalArgumentException(
LocalizedFormats.NOT_POSITIVE_POPULATION_SIZE, size);
}
populationSize = size;
}
/**
* Modify the sample size.
*
* @param size the new sample size.
* @throws IllegalArgumentException if <code>size</code> is negative.
* @deprecated as of 2.1 (class will become immutable in 3.0)
*/
@Deprecated
public void setSampleSize(int size) {
setSampleSizeInternal(size);
}
/**
* Modify the sample size.
*
* @param size the new sample size.
* @throws IllegalArgumentException if <code>size</code> is negative.
*/
private void setSampleSizeInternal(int size) {
if (size < 0) {
throw MathRuntimeException.createIllegalArgumentException(
LocalizedFormats.NOT_POSITIVE_SAMPLE_SIZE, size);
}
sampleSize = size;
}
/**
* For this distribution, X, this method returns P(X &ge; x).
*
* @param x the value at which the CDF is evaluated.
* @return upper tail CDF for this distribution.
* @since 1.1 * @since 1.1
*/ */
public double upperCumulativeProbability(int x) { public double upperCumulativeProbability(int x) {
@ -322,28 +252,31 @@ public class HypergeometricDistributionImpl extends AbstractIntegerDistribution
} else if (x > domain[1]) { } else if (x > domain[1]) {
ret = 0.0; ret = 0.0;
} else { } else {
ret = innerCumulativeProbability(domain[1], x, -1, populationSize, numberOfSuccesses, sampleSize); ret = innerCumulativeProbability(domain[1], x, -1, populationSize,
numberOfSuccesses, sampleSize);
} }
return ret; return ret;
} }
/** /**
* For this distribution, X, this method returns P(x0 &le; X &le; x1). This * For this distribution, {@code X}, this method returns
* probability is computed by summing the point probabilities for the values * {@code P(x0 <= X <= x1)}.
* x0, x0 + 1, x0 + 2, ..., x1, in the order directed by dx. * This probability is computed by summing the point probabilities for the
* values {@code x0, x0 + 1, x0 + 2, ..., x1}, in the order directed by
* {@code dx}.
* *
* @param x0 the inclusive, lower bound * @param x0 Inclusive lower bound.
* @param x1 the inclusive, upper bound * @param x1 Inclusive upper bound.
* @param dx the direction of summation. 1 indicates summing from x0 to x1. * @param dx Direction of summation (1 indicates summing from x0 to x1, and
* 0 indicates summing from x1 to x0. * 0 indicates summing from x1 to x0).
* @param n the population size. * @param n the population size.
* @param m number of successes in the population. * @param m number of successes in the population.
* @param k the sample size. * @param k the sample size.
* @return P(x0 &le; X &le; x1). * @return {@code P(x0 <= X <= x1)}.
*/ */
private double innerCumulativeProbability(int x0, int x1, int dx, int n, private double innerCumulativeProbability(int x0, int x1, int dx,
int m, int k) { int n, int m, int k) {
double ret = probability(n, m, k, x0); double ret = probability(n, m, k, x0);
while (x0 != x1) { while (x0 != x1) {
x0 += dx; x0 += dx;

View File

@ -25,60 +25,96 @@ import org.apache.commons.math.MathException;
*/ */
public interface IntegerDistribution extends DiscreteDistribution { public interface IntegerDistribution extends DiscreteDistribution {
/** /**
* For a random variable X whose values are distributed according * For a random variable {@code X} whose values are distributed according
* to this distribution, this method returns P(X = x). In other words, this * to this distribution, this method returns {@code P(X = x)}. In other
* method represents the probability mass function for the distribution. * words, this method represents the probability mass function for the
* distribution.
* *
* @param x the value at which the probability density function is evaluated. * @param x Value at which the probability density function is evaluated.
* @return the value of the probability density function at x * @return the value of the probability density function at {@code x}.
*/ */
double probability(int x); double probability(int x);
/** /**
* For a random variable X whose values are distributed according * For a random variable {@code X} whose values are distributed according
* to this distribution, this method returns P(X &le; x). In other words, * to this distribution, this method returns {@code P(X < x)}. In other
* this method represents the probability distribution function, or PDF * words, this method represents the probability distribution function, or
* for the distribution. * PDF for the distribution.
* *
* @param x the value at which the PDF is evaluated. * @param x Value at which the PDF is evaluated.
* @return PDF for this distribution. * @return PDF for this distribution.
* @throws MathException if the cumulative probability can not be * @throws MathException if the cumulative probability cannot be
* computed due to convergence or other numerical errors. * computed due to convergence or other numerical errors.
*/ */
double cumulativeProbability(int x) throws MathException; double cumulativeProbability(int x) throws MathException;
/** /**
* For this distribution, X, this method returns P(x0 &le; X &le; x1). * For this distribution, {@code X}, this method returns
* {@code P(x0 < X < x1)}.
*
* @param x0 the inclusive, lower bound * @param x0 the inclusive, lower bound
* @param x1 the inclusive, upper bound * @param x1 the inclusive, upper bound
* @return the cumulative probability. * @return the cumulative probability.
* @throws MathException if the cumulative probability can not be * @throws MathException if the cumulative probability can not be
* computed due to convergence or other numerical errors. * computed due to convergence or other numerical errors.
* @throws IllegalArgumentException if x0 > x1 * @throws IllegalArgumentException if {@code x0 > x1}.
*/ */
double cumulativeProbability(int x0, int x1) throws MathException; double cumulativeProbability(int x0, int x1) throws MathException;
/** /**
* For this distribution, X, this method returns the largest x such that * For this distribution, {@code X}, this method returns the largest
* P(X &le; x) <= p. * {@code x} such that {@code P(X < x) <= p}.
* <p> * <br/>
* Note that this definition implies: <ul> * Note that this definition implies:
* <li> If there is a minimum value, <code>m</code>, with positive * <ul>
* probability under (the density of) X, then <code>m - 1</code> is * <li> If there is a minimum value, {@code m}, with positive
* returned by <code>inverseCumulativeProbability(0).</code> If there is * probability under (the density of) {@code X}, then {@code m - 1} is
* no such value <code>m, Integer.MIN_VALUE</code> is * returned by {@code inverseCumulativeProbability(0).} If there is
* returned.</li> * no such value {@code m}, {@code Integer.MIN_VALUE} is returned.
* <li> If there is a maximum value, <code>M</code>, such that * </li>
* P(X &le; M) =1, then <code>M</code> is returned by * <li> If there is a maximum value, {@code M}, such that
* <code>inverseCumulativeProbability(1).</code> * {@code P(X < M) = 1}, then {@code M} is returned by
* If there is no such value, <code>M, Integer.MAX_VALUE</code> is * {@code inverseCumulativeProbability(1)}.
* returned.</li></ul></p> * If there is no such value, {@code M}, {@code Integer.MAX_VALUE} is
* returned.
* </li>
* </ul>
* *
* @param p the cumulative probability. * @param p Cumulative probability.
* @return the largest x such that P(X &le; x) <= p * @return the largest {@code x} such that {@code P(X < x) <= p}.
* @throws MathException if the inverse cumulative probability can not be * @throws MathException if the inverse cumulative probability cannot be
* computed due to convergence or other numerical errors. * computed due to convergence or other numerical errors.
* @throws IllegalArgumentException if p is not between 0 and 1 (inclusive) * @throws IllegalArgumentException if {@code p} is not between 0 and 1
* (inclusive).
*/ */
int inverseCumulativeProbability(double p) throws MathException; int inverseCumulativeProbability(double p) throws MathException;
/**
* Reseed the random generator used to generate samples.
*
* @param seed New seed.
* @since 3.0
*/
void reseedRandomGenerator(long seed);
/**
* Generate a random value sampled from this distribution.
*
* @return a random value.
* @throws MathException if an error occurs generating the random value.
* @since 3.0
*/
int sample() throws MathException;
/**
* Generate a random sample from the distribution.
*
* @param sampleSize number of random values to generate.
* @return an array representing the random sample.
* @throws MathException if an error occurs generating the sample.
* @throws org.apache.commons.math.exception.NotStrictlyPositiveException
* if {@code sampleSize} is not positive.
* @since 3.0
*/
int[] sample(int sampleSize) throws MathException;
} }

View File

@ -35,7 +35,7 @@ import org.apache.commons.math.util.FastMath;
public class NormalDistributionImpl extends AbstractContinuousDistribution public class NormalDistributionImpl extends AbstractContinuousDistribution
implements NormalDistribution, Serializable { implements NormalDistribution, Serializable {
/** /**
* Default inverse cumulative probability accuracy * Default inverse cumulative probability accuracy.
* @since 2.1 * @since 2.1
*/ */
public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9; public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
@ -44,9 +44,9 @@ public class NormalDistributionImpl extends AbstractContinuousDistribution
/** &sqrt;(2 &pi;) */ /** &sqrt;(2 &pi;) */
private static final double SQRT2PI = FastMath.sqrt(2 * FastMath.PI); private static final double SQRT2PI = FastMath.sqrt(2 * FastMath.PI);
/** Mean of this distribution. */ /** Mean of this distribution. */
private double mean = 0; private final double mean;
/** Standard deviation of this distribution. */ /** Standard deviation of this distribution. */
private double standardDeviation = 1; private final double standardDeviation;
/** Inverse cumulative probability accuracy. */ /** Inverse cumulative probability accuracy. */
private final double solverAbsoluteAccuracy; private final double solverAbsoluteAccuracy;

View File

@ -42,32 +42,14 @@ public interface PascalDistribution extends IntegerDistribution {
/** /**
* Access the number of successes for this distribution. * Access the number of successes for this distribution.
* *
* @return the number of successes * @return the number of successes.
*/ */
int getNumberOfSuccesses(); int getNumberOfSuccesses();
/** /**
* Access the probability of success for this distribution. * Access the probability of success for this distribution.
* *
* @return the probability of success * @return the probability of success.
*/ */
double getProbabilityOfSuccess(); double getProbabilityOfSuccess();
/**
* Change the number of successes for this distribution.
*
* @param successes the new number of successes
* @deprecated as of v2.1
*/
@Deprecated
void setNumberOfSuccesses(int successes);
/**
* Change the probability of success for this distribution.
*
* @param p the new probability of success
* @deprecated as of v2.1
*/
@Deprecated
void setProbabilityOfSuccess(double p);
} }

View File

@ -19,7 +19,8 @@ package org.apache.commons.math.distribution;
import java.io.Serializable; import java.io.Serializable;
import org.apache.commons.math.MathException; import org.apache.commons.math.MathException;
import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.exception.OutOfRangeException;
import org.apache.commons.math.exception.NotPositiveException;
import org.apache.commons.math.exception.util.LocalizedFormats; import org.apache.commons.math.exception.util.LocalizedFormats;
import org.apache.commons.math.special.Beta; import org.apache.commons.math.special.Beta;
import org.apache.commons.math.util.MathUtils; import org.apache.commons.math.util.MathUtils;
@ -32,101 +33,53 @@ import org.apache.commons.math.util.FastMath;
*/ */
public class PascalDistributionImpl extends AbstractIntegerDistribution public class PascalDistributionImpl extends AbstractIntegerDistribution
implements PascalDistribution, Serializable { implements PascalDistribution, Serializable {
/** Serializable version identifier. */
/** Serializable version identifier */
private static final long serialVersionUID = 6751309484392813623L; private static final long serialVersionUID = 6751309484392813623L;
/** The number of successes. */
/** The number of successes */ private final int numberOfSuccesses;
private int numberOfSuccesses; /** The probability of success. */
private final double probabilityOfSuccess;
/** The probability of success */
private double probabilityOfSuccess;
/** /**
* Create a Pascal distribution with the given number of trials and * Create a Pascal distribution with the given number of trials and
* probability of success. * probability of success.
* @param r the number of successes *
* @param p the probability of success * @param r Number of successes.
* @param p Probability of success.
*/ */
public PascalDistributionImpl(int r, double p) { public PascalDistributionImpl(int r, double p) {
super(); if (r < 0) {
setNumberOfSuccessesInternal(r); throw new NotPositiveException(LocalizedFormats.NUMBER_OF_SUCCESSES,
setProbabilityOfSuccessInternal(p); r);
}
if (p < 0 || p > 1) {
throw new OutOfRangeException(p, 0, 1);
}
numberOfSuccesses = r;
probabilityOfSuccess = p;
} }
/** /**
* Access the number of successes for this distribution. * {@inheritDoc}
* @return the number of successes
*/ */
public int getNumberOfSuccesses() { public int getNumberOfSuccesses() {
return numberOfSuccesses; return numberOfSuccesses;
} }
/** /**
* Access the probability of success for this distribution. * {@inheritDoc}
* @return the probability of success
*/ */
public double getProbabilityOfSuccess() { public double getProbabilityOfSuccess() {
return probabilityOfSuccess; return probabilityOfSuccess;
} }
/** /**
* Change the number of successes for this distribution. * Access the domain value lower bound, based on {@code p}, used to
* @param successes the new number of successes
* @throws IllegalArgumentException if <code>successes</code> is not
* positive.
* @deprecated as of 2.1 (class will become immutable in 3.0)
*/
@Deprecated
public void setNumberOfSuccesses(int successes) {
setNumberOfSuccessesInternal(successes);
}
/**
* Change the number of successes for this distribution.
* @param successes the new number of successes
* @throws IllegalArgumentException if <code>successes</code> is not
* positive.
*/
private void setNumberOfSuccessesInternal(int successes) {
if (successes < 0) {
throw MathRuntimeException.createIllegalArgumentException(
LocalizedFormats.NEGATIVE_NUMBER_OF_SUCCESSES,
successes);
}
numberOfSuccesses = successes;
}
/**
* Change the probability of success for this distribution.
* @param p the new probability of success
* @throws IllegalArgumentException if <code>p</code> is not a valid
* probability.
* @deprecated as of 2.1 (class will become immutable in 3.0)
*/
@Deprecated
public void setProbabilityOfSuccess(double p) {
setProbabilityOfSuccessInternal(p);
}
/**
* Change the probability of success for this distribution.
* @param p the new probability of success
* @throws IllegalArgumentException if <code>p</code> is not a valid
* probability.
*/
private void setProbabilityOfSuccessInternal(double p) {
if (p < 0.0 || p > 1.0) {
throw MathRuntimeException.createIllegalArgumentException(
LocalizedFormats.OUT_OF_RANGE_SIMPLE, p, 0.0, 1.0);
}
probabilityOfSuccess = p;
}
/**
* Access the domain value lower bound, based on <code>p</code>, used to
* bracket a PDF root. * bracket a PDF root.
* @param p the desired probability for the critical value *
* @return domain value lower bound, i.e. P(X &lt; <i>lower bound</i>) &lt; * @param p Desired probability for the critical value.
* <code>p</code> * @return the domain value lower bound, i.e. {@code P(X < 'lower bound') < p}.
*/ */
@Override @Override
protected int getDomainLowerBound(double p) { protected int getDomainLowerBound(double p) {
@ -134,11 +87,11 @@ public class PascalDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* Access the domain value upper bound, based on <code>p</code>, used to * Access the domain value upper bound, based on {@code p}, used to
* bracket a PDF root. * bracket a PDF root.
* @param p the desired probability for the critical value *
* @return domain value upper bound, i.e. P(X &lt; <i>upper bound</i>) &gt; * @param p Desired probability for the critical value
* <code>p</code> * @return the domain value upper bound, i.e. {@code P(X < 'upper bound') > p}.
*/ */
@Override @Override
protected int getDomainUpperBound(double p) { protected int getDomainUpperBound(double p) {
@ -147,11 +100,12 @@ public class PascalDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* For this distribution, X, this method returns P(X &le; x). * For this distribution, {@code X}, this method returns {@code P(X < x)}.
* @param x the value at which the PDF is evaluated *
* @return PDF for this distribution * @param x Value at which the PDF is evaluated.
* @return PDF for this distribution.
* @throws MathException if the cumulative probability can not be computed * @throws MathException if the cumulative probability can not be computed
* due to convergence or other numerical errors * due to convergence or other numerical errors.
*/ */
@Override @Override
public double cumulativeProbability(int x) throws MathException { public double cumulativeProbability(int x) throws MathException {
@ -166,9 +120,10 @@ public class PascalDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* For this distribution, X, this method returns P(X = x). * For this distribution, {@code X}, this method returns {@code P(X = x)}.
* @param x the value at which the PMF is evaluated *
* @return PMF for this distribution * @param x Value at which the PMF is evaluated.
* @return PMF for this distribution.
*/ */
public double probability(int x) { public double probability(int x) {
double ret; double ret;
@ -184,16 +139,15 @@ public class PascalDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* For this distribution, X, this method returns the largest x, such that * For this distribution, {@code X}, this method returns the largest
* P(X &le; x) &le; <code>p</code>. * {@code x}, such that {@code P(X < x) p}.
* <p> * It will return -1 when p = 0 and {@code Integer.MAX_VALUE} when p = 1.
* Returns <code>-1</code> for p=0 and <code>Integer.MAX_VALUE</code> *
* for p=1.</p> * @param p Desired probability.
* @param p the desired probability * @return the largest {@code x} such that {@code P(X < x) <= p}.
* @return the largest x such that P(X &le; x) <= p
* @throws MathException if the inverse cumulative probability can not be * @throws MathException if the inverse cumulative probability can not be
* computed due to convergence or other numerical errors. * computed due to convergence or other numerical errors.
* @throws IllegalArgumentException if p < 0 or p > 1 * @throws OutOfRangeException if {@code p < 0} or {@code p > 1}.
*/ */
@Override @Override
public int inverseCumulativeProbability(final double p) public int inverseCumulativeProbability(final double p)

View File

@ -31,50 +31,41 @@ import org.apache.commons.math.util.FastMath;
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
public class PoissonDistributionImpl extends AbstractIntegerDistribution public class PoissonDistributionImpl extends AbstractIntegerDistribution
implements PoissonDistribution, Serializable { implements PoissonDistribution, Serializable {
/** /**
* Default maximum number of iterations for cumulative probability calculations. * Default maximum number of iterations for cumulative probability calculations.
* @since 2.1 * @since 2.1
*/ */
public static final int DEFAULT_MAX_ITERATIONS = 10000000; public static final int DEFAULT_MAX_ITERATIONS = 10000000;
/** /**
* Default convergence criterion. * Default convergence criterion.
* @since 2.1 * @since 2.1
*/ */
public static final double DEFAULT_EPSILON = 1E-12; public static final double DEFAULT_EPSILON = 1e-12;
/** Serializable version identifier. */
/** Serializable version identifier */
private static final long serialVersionUID = -3349935121172596109L; private static final long serialVersionUID = -3349935121172596109L;
/** Distribution used to compute normal approximation. */ /** Distribution used to compute normal approximation. */
private NormalDistribution normal; private final NormalDistribution normal;
/** Mean of the distribution. */
/** private final double mean;
* Holds the Poisson mean for the distribution.
*/
private double mean;
/** /**
* Maximum number of iterations for cumulative probability. * Maximum number of iterations for cumulative probability.
* *
* Cumulative probabilities are estimated using either Lanczos series approximation of * Cumulative probabilities are estimated using either Lanczos series approximation of
* Gamma#regularizedGammaP or continued fraction approximation of Gamma#regularizedGammaQ. * Gamma#regularizedGammaP or continued fraction approximation of Gamma#regularizedGammaQ.
*/ */
private int maxIterations = DEFAULT_MAX_ITERATIONS; private final int maxIterations;
/** /**
* Convergence criterion for cumulative probability. * Convergence criterion for cumulative probability.
*/ */
private double epsilon = DEFAULT_EPSILON; private final double epsilon;
/** /**
* Create a new Poisson distribution with the given the mean. The mean value * Create a new Poisson distribution with the given the mean. The mean value
* must be positive; otherwise an <code>IllegalArgument</code> is thrown. * must be positive; otherwise an <code>IllegalArgument</code> is thrown.
* *
* @param p the Poisson mean * @param p the Poisson mean
* @throws IllegalArgumentException if p &le; 0 * @throws NotStrictlyPositiveException if {@code p <= 0}.
*/ */
public PoissonDistributionImpl(double p) { public PoissonDistributionImpl(double p) {
this(p, DEFAULT_EPSILON, DEFAULT_MAX_ITERATIONS); this(p, DEFAULT_EPSILON, DEFAULT_MAX_ITERATIONS);
@ -84,9 +75,10 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution
* Create a new Poisson distribution with the given mean, convergence criterion * Create a new Poisson distribution with the given mean, convergence criterion
* and maximum number of iterations. * and maximum number of iterations.
* *
* @param p the Poisson mean * @param p Poisson mean.
* @param epsilon the convergence criteria for cumulative probabilites * @param epsilon Convergence criterion for cumulative probabilities.
* @param maxIterations the maximum number of iterations for cumulative probabilites * @param maxIterations the maximum number of iterations for cumulative
* probabilities.
* @since 2.1 * @since 2.1
*/ */
public PoissonDistributionImpl(double p, double epsilon, int maxIterations) { public PoissonDistributionImpl(double p, double epsilon, int maxIterations) {
@ -102,8 +94,8 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution
/** /**
* Create a new Poisson distribution with the given mean and convergence criterion. * Create a new Poisson distribution with the given mean and convergence criterion.
* *
* @param p the Poisson mean * @param p Poisson mean.
* @param epsilon the convergence criteria for cumulative probabilites * @param epsilon Convergence criterion for cumulative probabilities.
* @since 2.1 * @since 2.1
*/ */
public PoissonDistributionImpl(double p, double epsilon) { public PoissonDistributionImpl(double p, double epsilon) {
@ -113,8 +105,8 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution
/** /**
* Create a new Poisson distribution with the given mean and maximum number of iterations. * Create a new Poisson distribution with the given mean and maximum number of iterations.
* *
* @param p the Poisson mean * @param p Poisson mean.
* @param maxIterations the maximum number of iterations for cumulative probabilites * @param maxIterations Maximum number of iterations for cumulative probabilities.
* @since 2.1 * @since 2.1
*/ */
public PoissonDistributionImpl(double p, int maxIterations) { public PoissonDistributionImpl(double p, int maxIterations) {
@ -122,20 +114,17 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* Get the Poisson mean for the distribution. * {@inheritDoc}
*
* @return the Poisson mean for the distribution.
*/ */
public double getMean() { public double getMean() {
return mean; return mean;
} }
/** /**
* The probability mass function P(X = x) for a Poisson distribution. * The probability mass function {@code P(X = x)} for a Poisson distribution.
* *
* @param x the value at which the probability density function is * @param x Value at which the probability density function is evaluated.
* evaluated. * @return the value of the probability mass function at {@code x}.
* @return the value of the probability mass function at x
*/ */
public double probability(int x) { public double probability(int x) {
double ret; double ret;
@ -152,13 +141,13 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* The probability distribution function P(X <= x) for a Poisson * The probability distribution function {@code P(X <= x)} for a Poisson
* distribution. * distribution.
* *
* @param x the value at which the PDF is evaluated. * @param x Value at which the PDF is evaluated.
* @return Poisson distribution function evaluated at x * @return the Poisson distribution function evaluated at {@code x}.
* @throws MathException if the cumulative probability can not be computed * @throws MathException if the cumulative probability cannot be computed
* due to convergence or other numerical errors. * due to convergence or other numerical errors.
*/ */
@Override @Override
public double cumulativeProbability(int x) throws MathException { public double cumulativeProbability(int x) throws MathException {
@ -173,18 +162,16 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution
/** /**
* Calculates the Poisson distribution function using a normal * Calculates the Poisson distribution function using a normal
* approximation. The <code>N(mean, sqrt(mean))</code> distribution is used * approximation. The {@code N(mean, sqrt(mean))} distribution is used
* to approximate the Poisson distribution. * to approximate the Poisson distribution.
* <p> * The computation uses "half-correction" (evaluating the normal
* The computation uses "half-correction" -- evaluating the normal * distribution function at {@code x + 0.5}).
* distribution function at <code>x + 0.5</code>
* </p>
* *
* @param x the upper bound, inclusive * @param x Upper bound, inclusive.
* @return the distribution function value calculated using a normal * @return the distribution function value calculated using a normal
* approximation * approximation.
* @throws MathException if an error occurs computing the normal * @throws MathException if an error occurs computing the normal
* approximation * approximation.
*/ */
public double normalApproximateProbability(int x) throws MathException { public double normalApproximateProbability(int x) throws MathException {
// calculate the probability using half-correction // calculate the probability using half-correction
@ -193,20 +180,25 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution
/** /**
* Generates a random value sampled from this distribution. * Generates a random value sampled from this distribution.
* <br/>
* <strong>Algorithm Description</strong>:
* <ul>
* <li>For small means, uses simulation of a Poisson process
* using Uniform deviates, as described
* <a href="http://irmi.epfl.ch/cmos/Pmmi/interactive/rng7.htm"> here</a>.
* The Poisson process (and hence value returned) is bounded by 1000 * mean.
* </li>
* <li>For large means, uses the rejection algorithm described in
* <quote>
* Devroye, Luc. (1981).<i>The Computer Generation of Poisson Random Variables</i>
* <strong>Computing</strong> vol. 26 pp. 197-207.
* </quote>
* </li>
* </ul>
* *
* <p><strong>Algorithm Description</strong>: * @return a random value.
* <ul><li> For small means, uses simulation of a Poisson process
* using Uniform deviates, as described
* <a href="http://irmi.epfl.ch/cmos/Pmmi/interactive/rng7.htm"> here.</a>
* The Poisson process (and hence value returned) is bounded by 1000 * mean.</li><
*
* <li> For large means, uses the rejection algorithm described in <br/>
* Devroye, Luc. (1981).<i>The Computer Generation of Poisson Random Variables</i>
* <strong>Computing</strong> vol. 26 pp. 197-207.</li></ul></p>
*
* @return random value
* @since 2.2 * @since 2.2
* @throws MathException if an error occurs generating the random value * @throws MathException if an error occurs generating the random value.
*/ */
@Override @Override
public int sample() throws MathException { public int sample() throws MathException {
@ -214,12 +206,12 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* Access the domain value lower bound, based on <code>p</code>, used to * Access the domain value lower bound, based on {@code p}, used to
* bracket a CDF root. This method is used by * bracket a CDF root. This method is used by
* {@link #inverseCumulativeProbability(double)} to find critical values. * {@link #inverseCumulativeProbability(double)} to find critical values.
* *
* @param p the desired probability for the critical value * @param p Desired probability for the critical value.
* @return domain lower bound * @return the domain lower bound.
*/ */
@Override @Override
protected int getDomainLowerBound(double p) { protected int getDomainLowerBound(double p) {
@ -227,12 +219,12 @@ public class PoissonDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* Access the domain value upper bound, based on <code>p</code>, used to * Access the domain value upper bound, based on {@code p}, used to
* bracket a CDF root. This method is used by * bracket a CDF root. This method is used by
* {@link #inverseCumulativeProbability(double)} to find critical values. * {@link #inverseCumulativeProbability(double)} to find critical values.
* *
* @param p the desired probability for the critical value * @param p Desired probability for the critical value.
* @return domain upper bound * @return the domain upper bound.
*/ */
@Override @Override
protected int getDomainUpperBound(double p) { protected int getDomainUpperBound(double p) {

View File

@ -42,7 +42,7 @@ public class TDistributionImpl
/** Serializable version identifier */ /** Serializable version identifier */
private static final long serialVersionUID = -5852615386664158222L; private static final long serialVersionUID = -5852615386664158222L;
/** The degrees of freedom. */ /** The degrees of freedom. */
private double degreesOfFreedom; private final double degreesOfFreedom;
/** Inverse cumulative probability accuracy. */ /** Inverse cumulative probability accuracy. */
private final double solverAbsoluteAccuracy; private final double solverAbsoluteAccuracy;

View File

@ -32,18 +32,18 @@ import org.apache.commons.math.util.FastMath;
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
public class WeibullDistributionImpl extends AbstractContinuousDistribution public class WeibullDistributionImpl extends AbstractContinuousDistribution
implements WeibullDistribution, Serializable { implements WeibullDistribution, Serializable {
/** /**
* Default inverse cumulative probability accuracy * Default inverse cumulative probability accuracy.
* @since 2.1 * @since 2.1
*/ */
public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9; public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
/** Serializable version identifier */ /** Serializable version identifier. */
private static final long serialVersionUID = 8589540077390120676L; private static final long serialVersionUID = 8589540077390120676L;
/** The shape parameter. */ /** The shape parameter. */
private double shape; private final double shape;
/** The scale parameter. */ /** The scale parameter. */
private double scale; private final double scale;
/** Inverse cumulative probability accuracy. */ /** Inverse cumulative probability accuracy. */
private final double solverAbsoluteAccuracy; private final double solverAbsoluteAccuracy;

View File

@ -30,7 +30,6 @@ package org.apache.commons.math.distribution;
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
public interface ZipfDistribution extends IntegerDistribution { public interface ZipfDistribution extends IntegerDistribution {
/** /**
* Get the number of elements (e.g. corpus size) for the distribution. * Get the number of elements (e.g. corpus size) for the distribution.
* *
@ -38,34 +37,10 @@ public interface ZipfDistribution extends IntegerDistribution {
*/ */
int getNumberOfElements(); int getNumberOfElements();
/**
* Set the number of elements (e.g. corpus size) for the distribution.
* The parameter value must be positive; otherwise an
* <code>IllegalArgumentException</code> is thrown.
*
* @param n the number of elements
* @throws IllegalArgumentException if n &le; 0
* @deprecated as of v2.1
*/
@Deprecated
void setNumberOfElements(int n);
/** /**
* Get the exponent characterising the distribution. * Get the exponent characterising the distribution.
* *
* @return the exponent * @return the exponent
*/ */
double getExponent(); double getExponent();
/**
* Set the exponent characterising the distribution.
* The parameter value must be positive; otherwise an
* <code>IllegalArgumentException</code> is thrown.
*
* @param s the exponent
* @throws IllegalArgumentException if s &le; 0.0
* @deprecated as of v2.1
*/
@Deprecated
void setExponent(double s);
} }

View File

@ -19,7 +19,7 @@ package org.apache.commons.math.distribution;
import java.io.Serializable; import java.io.Serializable;
import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.exception.NotStrictlyPositiveException;
import org.apache.commons.math.exception.util.LocalizedFormats; import org.apache.commons.math.exception.util.LocalizedFormats;
import org.apache.commons.math.util.FastMath; import org.apache.commons.math.util.FastMath;
@ -30,115 +30,56 @@ import org.apache.commons.math.util.FastMath;
*/ */
public class ZipfDistributionImpl extends AbstractIntegerDistribution public class ZipfDistributionImpl extends AbstractIntegerDistribution
implements ZipfDistribution, Serializable { implements ZipfDistribution, Serializable {
/** Serializable version identifier. */ /** Serializable version identifier. */
private static final long serialVersionUID = -140627372283420404L; private static final long serialVersionUID = -140627372283420404L;
/** Number of elements. */ /** Number of elements. */
private int numberOfElements; private final int numberOfElements;
/** Exponent parameter of the distribution. */ /** Exponent parameter of the distribution. */
private double exponent; private final double exponent;
/** /**
* Create a new Zipf distribution with the given number of elements and * Create a new Zipf distribution with the given number of elements and
* exponent. Both values must be positive; otherwise an * exponent.
* <code>IllegalArgumentException</code> is thrown.
* *
* @param numberOfElements the number of elements * @param numberOfElements Number of elements.
* @param exponent the exponent * @param exponent Exponent.
* @exception IllegalArgumentException if n &le; 0 or s &le; 0.0 * @exception NotStrictlyPositiveException if {@code numberOfElements <= 0}
* or {@code exponent <= 0}.
*/ */
public ZipfDistributionImpl(final int numberOfElements, final double exponent) public ZipfDistributionImpl(final int numberOfElements,
throws IllegalArgumentException { final double exponent) {
setNumberOfElementsInternal(numberOfElements); if (numberOfElements <= 0) {
setExponentInternal(exponent); throw new NotStrictlyPositiveException(LocalizedFormats.DIMENSION,
numberOfElements);
}
if (exponent <= 0) {
throw new NotStrictlyPositiveException(LocalizedFormats.EXPONENT,
exponent);
}
this.numberOfElements = numberOfElements;
this.exponent = exponent;
} }
/** /**
* Get the number of elements (e.g. corpus size) for the distribution. * {@inheritDoc}
*
* @return the number of elements
*/ */
public int getNumberOfElements() { public int getNumberOfElements() {
return numberOfElements; return numberOfElements;
} }
/** /**
* Set the number of elements (e.g. corpus size) for the distribution. * {@inheritDoc}
* The parameter value must be positive; otherwise an
* <code>IllegalArgumentException</code> is thrown.
*
* @param n the number of elements
* @exception IllegalArgumentException if n &le; 0
* @deprecated as of 2.1 (class will become immutable in 3.0)
*/
@Deprecated
public void setNumberOfElements(final int n) {
setNumberOfElementsInternal(n);
}
/**
* Set the number of elements (e.g. corpus size) for the distribution.
* The parameter value must be positive; otherwise an
* <code>IllegalArgumentException</code> is thrown.
*
* @param n the number of elements
* @exception IllegalArgumentException if n &le; 0
*/
private void setNumberOfElementsInternal(final int n)
throws IllegalArgumentException {
if (n <= 0) {
throw MathRuntimeException.createIllegalArgumentException(
LocalizedFormats.INSUFFICIENT_DIMENSION, n, 0);
}
this.numberOfElements = n;
}
/**
* Get the exponent characterising the distribution.
*
* @return the exponent
*/ */
public double getExponent() { public double getExponent() {
return exponent; return exponent;
} }
/** /**
* Set the exponent characterising the distribution. * The probability mass function {@code P(X = x)} for a Zipf distribution.
* The parameter value must be positive; otherwise an
* <code>IllegalArgumentException</code> is thrown.
* *
* @param s the exponent * @param x Value at which the probability density function is evaluated.
* @exception IllegalArgumentException if s &le; 0.0 * @return the value of the probability mass function at {@code x}.
* @deprecated as of 2.1 (class will become immutable in 3.0)
*/
@Deprecated
public void setExponent(final double s) {
setExponentInternal(s);
}
/**
* Set the exponent characterising the distribution.
* The parameter value must be positive; otherwise an
* <code>IllegalArgumentException</code> is thrown.
*
* @param s the exponent
* @exception IllegalArgumentException if s &le; 0.0
*/
private void setExponentInternal(final double s)
throws IllegalArgumentException {
if (s <= 0.0) {
throw MathRuntimeException.createIllegalArgumentException(
LocalizedFormats.NOT_POSITIVE_EXPONENT,
s);
}
this.exponent = s;
}
/**
* The probability mass function P(X = x) for a Zipf distribution.
*
* @param x the value at which the probability density function is evaluated.
* @return the value of the probability mass function at x
*/ */
public double probability(final int x) { public double probability(final int x) {
if (x <= 0 || x > numberOfElements) { if (x <= 0 || x > numberOfElements) {
@ -146,14 +87,14 @@ public class ZipfDistributionImpl extends AbstractIntegerDistribution
} }
return (1.0 / FastMath.pow(x, exponent)) / generalizedHarmonic(numberOfElements, exponent); return (1.0 / FastMath.pow(x, exponent)) / generalizedHarmonic(numberOfElements, exponent);
} }
/** /**
* The probability distribution function P(X <= x) for a Zipf distribution. * The probability distribution function {@code P(X <= x)} for a
* Zipf distribution.
* *
* @param x the value at which the PDF is evaluated. * @param x Value at which the PDF is evaluated.
* @return Zipf distribution function evaluated at x * @return Zipf distribution function evaluated at {@code x}.
*/ */
@Override @Override
public double cumulativeProbability(final int x) { public double cumulativeProbability(final int x) {
@ -164,16 +105,14 @@ public class ZipfDistributionImpl extends AbstractIntegerDistribution
} }
return generalizedHarmonic(x, exponent) / generalizedHarmonic(numberOfElements, exponent); return generalizedHarmonic(x, exponent) / generalizedHarmonic(numberOfElements, exponent);
} }
/** /**
* Access the domain value lower bound, based on <code>p</code>, used to * Access the domain value lower bound, based on {@code p}, used to
* bracket a PDF root. * bracket a PDF root.
* *
* @param p the desired probability for the critical value * @param p Desired probability for the critical value.
* @return domain value lower bound, i.e. * @return the domain value lower bound, i.e. {@code P(X < 'lower bound') < p}.
* P(X &lt; <i>lower bound</i>) &lt; <code>p</code>
*/ */
@Override @Override
protected int getDomainLowerBound(final double p) { protected int getDomainLowerBound(final double p) {
@ -181,27 +120,25 @@ public class ZipfDistributionImpl extends AbstractIntegerDistribution
} }
/** /**
* Access the domain value upper bound, based on <code>p</code>, used to * Access the domain value upper bound, based on {@code p}, used to
* bracket a PDF root. * bracket a PDF root.
* *
* @param p the desired probability for the critical value * @param p Desired probability for the critical value
* @return domain value upper bound, i.e. * @return the domain value upper bound, i.e. {@code P(X < 'upper bound') > p}.
* P(X &lt; <i>upper bound</i>) &gt; <code>p</code>
*/ */
@Override @Override
protected int getDomainUpperBound(final double p) { protected int getDomainUpperBound(final double p) {
return numberOfElements; return numberOfElements;
} }
/** /**
* Calculates the Nth generalized harmonic number. See * Calculates the Nth generalized harmonic number. See
* <a href="http://mathworld.wolfram.com/HarmonicSeries.html">Harmonic * <a href="http://mathworld.wolfram.com/HarmonicSeries.html">Harmonic
* Series</a>. * Series</a>.
* *
* @param n the term in the series to calculate (must be &ge; 1) * @param n Term in the series to calculate (must be larger than 1)
* @param m the exponent; special case m == 1.0 is the harmonic series * @param m Exponent (special case {@code m = 1} is the harmonic series).
* @return the nth generalized harmonic number * @return the n<sup>th</sup> generalized harmonic number.
*/ */
private double generalizedHarmonic(final int n, final double m) { private double generalizedHarmonic(final int n, final double m) {
double value = 0; double value = 0;
@ -210,5 +147,4 @@ public class ZipfDistributionImpl extends AbstractIntegerDistribution
} }
return value; return value;
} }
} }

View File

@ -119,6 +119,7 @@ public enum LocalizedFormats implements Localizable {
INSTANCES_NOT_COMPARABLE_TO_EXISTING_VALUES("instance of class {0} not comparable to existing values"), INSTANCES_NOT_COMPARABLE_TO_EXISTING_VALUES("instance of class {0} not comparable to existing values"),
INSUFFICIENT_DATA_FOR_T_STATISTIC("insufficient data for t statistic, needs at least 2, got {0}"), INSUFFICIENT_DATA_FOR_T_STATISTIC("insufficient data for t statistic, needs at least 2, got {0}"),
INSUFFICIENT_DIMENSION("insufficient dimension {0}, must be at least {1}"), INSUFFICIENT_DIMENSION("insufficient dimension {0}, must be at least {1}"),
DIMENSION("dimension ({0})"), /* keep */
INSUFFICIENT_OBSERVED_POINTS_IN_SAMPLE("sample contains {0} observed points, at least {1} are required"), INSUFFICIENT_OBSERVED_POINTS_IN_SAMPLE("sample contains {0} observed points, at least {1} are required"),
INSUFFICIENT_ROWS_AND_COLUMNS("insufficient data: only {0} rows and {1} columns."), INSUFFICIENT_ROWS_AND_COLUMNS("insufficient data: only {0} rows and {1} columns."),
INTEGRATION_METHOD_NEEDS_AT_LEAST_ONE_PREVIOUS_POINT("{0} method needs at least one previous point"), INTEGRATION_METHOD_NEEDS_AT_LEAST_ONE_PREVIOUS_POINT("{0} method needs at least one previous point"),
@ -150,7 +151,9 @@ public enum LocalizedFormats implements Localizable {
NEGATIVE_ELEMENT_AT_2D_INDEX("element ({0}, {1}) is negative: {2}"), NEGATIVE_ELEMENT_AT_2D_INDEX("element ({0}, {1}) is negative: {2}"),
NEGATIVE_ELEMENT_AT_INDEX("element {0} is negative: {1}"), NEGATIVE_ELEMENT_AT_INDEX("element {0} is negative: {1}"),
NEGATIVE_NUMBER_OF_SUCCESSES("number of successes must be non-negative ({0})"), NEGATIVE_NUMBER_OF_SUCCESSES("number of successes must be non-negative ({0})"),
NUMBER_OF_SUCCESSES("number of successes ({0})"), /* keep */
NEGATIVE_NUMBER_OF_TRIALS("number of trials must be non-negative ({0})"), NEGATIVE_NUMBER_OF_TRIALS("number of trials must be non-negative ({0})"),
NUMBER_OF_TRIALS("number of trials ({0})"),
NEGATIVE_ROBUSTNESS_ITERATIONS("the number of robustness iterations must be non-negative, but got {0}"), NEGATIVE_ROBUSTNESS_ITERATIONS("the number of robustness iterations must be non-negative, but got {0}"),
START_POSITION("start position ({0})"), /* keep */ START_POSITION("start position ({0})"), /* keep */
NON_CONVERGENT_CONTINUED_FRACTION("Continued fraction convergents failed to converge for value {0}"), NON_CONVERGENT_CONTINUED_FRACTION("Continued fraction convergents failed to converge for value {0}"),
@ -178,6 +181,7 @@ public enum LocalizedFormats implements Localizable {
NOT_POSITIVE_DEGREES_OF_FREEDOM("degrees of freedom must be positive ({0})"), NOT_POSITIVE_DEGREES_OF_FREEDOM("degrees of freedom must be positive ({0})"),
NOT_POSITIVE_ELEMENT_AT_INDEX("element {0} is not positive: {1}"), NOT_POSITIVE_ELEMENT_AT_INDEX("element {0} is not positive: {1}"),
NOT_POSITIVE_EXPONENT("invalid exponent {0} (must be positive)"), NOT_POSITIVE_EXPONENT("invalid exponent {0} (must be positive)"),
EXPONENT("exponent ({0})"), /* keep */
NOT_POSITIVE_LENGTH("length must be positive ({0})"), NOT_POSITIVE_LENGTH("length must be positive ({0})"),
LENGTH("length ({0})"), /* keep */ LENGTH("length ({0})"), /* keep */
NOT_POSITIVE_MEAN("mean must be positive ({0})"), NOT_POSITIVE_MEAN("mean must be positive ({0})"),
@ -188,6 +192,7 @@ public enum LocalizedFormats implements Localizable {
PERMUTATION_SIZE("permutation size ({0}"), /* keep */ PERMUTATION_SIZE("permutation size ({0}"), /* keep */
NOT_POSITIVE_POISSON_MEAN("the Poisson mean must be positive ({0})"), NOT_POSITIVE_POISSON_MEAN("the Poisson mean must be positive ({0})"),
NOT_POSITIVE_POPULATION_SIZE("population size must be positive ({0})"), NOT_POSITIVE_POPULATION_SIZE("population size must be positive ({0})"),
POPULATION_SIZE("population size ({0})"), /* keep */
NOT_POSITIVE_ROW_DIMENSION("invalid row dimension: {0} (must be positive)"), NOT_POSITIVE_ROW_DIMENSION("invalid row dimension: {0} (must be positive)"),
NOT_POSITIVE_SAMPLE_SIZE("sample size must be positive ({0})"), NOT_POSITIVE_SAMPLE_SIZE("sample size must be positive ({0})"),
NOT_POSITIVE_SCALE("scale must be positive ({0})"), NOT_POSITIVE_SCALE("scale must be positive ({0})"),

View File

@ -91,6 +91,7 @@ INPUT_DATA_FROM_UNSUPPORTED_DATASOURCE = les donn\u00e9es d''entr\u00e9e provien
INSTANCES_NOT_COMPARABLE_TO_EXISTING_VALUES = l''instance de la classe {0} n''est pas comparable aux valeurs existantes INSTANCES_NOT_COMPARABLE_TO_EXISTING_VALUES = l''instance de la classe {0} n''est pas comparable aux valeurs existantes
INSUFFICIENT_DATA_FOR_T_STATISTIC = deux valeurs ou plus sont n\u00e9cessaires pour la statistique t, il y en a {0} INSUFFICIENT_DATA_FOR_T_STATISTIC = deux valeurs ou plus sont n\u00e9cessaires pour la statistique t, il y en a {0}
INSUFFICIENT_DIMENSION = dimension {0} insuffisante, elle devrait \u00eatre au moins {1} INSUFFICIENT_DIMENSION = dimension {0} insuffisante, elle devrait \u00eatre au moins {1}
DIMENSION = dimension ({0})
INSUFFICIENT_OBSERVED_POINTS_IN_SAMPLE = l''\u00e9chantillon ne contient que {0} points alors qu''au moins {1} sont n\u00e9cessaires INSUFFICIENT_OBSERVED_POINTS_IN_SAMPLE = l''\u00e9chantillon ne contient que {0} points alors qu''au moins {1} sont n\u00e9cessaires
INSUFFICIENT_ROWS_AND_COLUMNS = donn\u00e9es insuffisantes : seulement {0} lignes et {1} colonnes. INSUFFICIENT_ROWS_AND_COLUMNS = donn\u00e9es insuffisantes : seulement {0} lignes et {1} colonnes.
INTEGRATION_METHOD_NEEDS_AT_LEAST_ONE_PREVIOUS_POINT = la m\u00e9thode {0} n\u00e9cessite au moins un point pr\u00e9c\u00e9dent INTEGRATION_METHOD_NEEDS_AT_LEAST_ONE_PREVIOUS_POINT = la m\u00e9thode {0} n\u00e9cessite au moins un point pr\u00e9c\u00e9dent
@ -122,7 +123,9 @@ NEGATIVE_COMPLEX_MODULE = module n\u00e9gatif ({0}) pour un nombre complexe
NEGATIVE_ELEMENT_AT_2D_INDEX = l''\u00e9l\u00e9ment ({0}, {1}) est n\u00e9gatif : {2} NEGATIVE_ELEMENT_AT_2D_INDEX = l''\u00e9l\u00e9ment ({0}, {1}) est n\u00e9gatif : {2}
NEGATIVE_ELEMENT_AT_INDEX = l''\u00e9l\u00e9ment {0} est n\u00e9gatif : {1} NEGATIVE_ELEMENT_AT_INDEX = l''\u00e9l\u00e9ment {0} est n\u00e9gatif : {1}
NEGATIVE_NUMBER_OF_SUCCESSES = le nombre de succ\u00e8s ne doit pas \u00eatre n\u00e9gatif ({0}) NEGATIVE_NUMBER_OF_SUCCESSES = le nombre de succ\u00e8s ne doit pas \u00eatre n\u00e9gatif ({0})
NUMBER_OF_SUCCESSES = nombre de succ\u00e8s ({0})
NEGATIVE_NUMBER_OF_TRIALS = le nombre d''essais ne doit pas \u00eatre n\u00e9gatif ({0}) NEGATIVE_NUMBER_OF_TRIALS = le nombre d''essais ne doit pas \u00eatre n\u00e9gatif ({0})
NUMBER_OF_TRIALS = nombre d''essais ({0})
NEGATIVE_ROBUSTNESS_ITERATIONS = le nombre d''it\u00e9rations robuste ne peut \u00eatre n\u00e9gatif, alors qu''il est de {0} NEGATIVE_ROBUSTNESS_ITERATIONS = le nombre d''it\u00e9rations robuste ne peut \u00eatre n\u00e9gatif, alors qu''il est de {0}
START_POSITION = position de d\u00e9part START_POSITION = position de d\u00e9part
NON_CONVERGENT_CONTINUED_FRACTION = \u00c9chec de convergence de fraction continue pour la valeur {0} NON_CONVERGENT_CONTINUED_FRACTION = \u00c9chec de convergence de fraction continue pour la valeur {0}
@ -150,6 +153,7 @@ NOT_POSITIVE_DEGREES_OF_FREEDOM = les degr\u00e9s de libert\u00e9 doivent \u00ea
DEGREES_OF_FREEDOM = degr\u00e9s de libert\u00e9 ({0}) DEGREES_OF_FREEDOM = degr\u00e9s de libert\u00e9 ({0})
NOT_POSITIVE_ELEMENT_AT_INDEX = l''\u00e9l\u00e9ment {0} n''est pas positif : {1} NOT_POSITIVE_ELEMENT_AT_INDEX = l''\u00e9l\u00e9ment {0} n''est pas positif : {1}
NOT_POSITIVE_EXPONENT = exposant {0} invalide (doit \u00eatre positif) NOT_POSITIVE_EXPONENT = exposant {0} invalide (doit \u00eatre positif)
EXPONENT = exposant ({0})
NOT_POSITIVE_LENGTH = la longueur doit \u00eatre positive ({0}) NOT_POSITIVE_LENGTH = la longueur doit \u00eatre positive ({0})
LENGTH = longueur ({0}) LENGTH = longueur ({0})
NOT_POSITIVE_MEAN = la moyenne doit \u00eatre positive ({0}) NOT_POSITIVE_MEAN = la moyenne doit \u00eatre positive ({0})
@ -160,6 +164,7 @@ NOT_POSITIVE_PERMUTATION = la permutation k ({0}) doit \u00eatre positive
PERMUTATION_SIZE = taille de la permutation PERMUTATION_SIZE = taille de la permutation
NOT_POSITIVE_POISSON_MEAN = la moyenne de Poisson doit \u00eatre positive ({0}) NOT_POSITIVE_POISSON_MEAN = la moyenne de Poisson doit \u00eatre positive ({0})
NOT_POSITIVE_POPULATION_SIZE = la taille de la population doit \u00eatre positive ({0}) NOT_POSITIVE_POPULATION_SIZE = la taille de la population doit \u00eatre positive ({0})
POPULATION_SIZE = taille de la population ({0})
NOT_POSITIVE_ROW_DIMENSION = nombre de lignes invalide : {0} (doit \u00eatre positif) NOT_POSITIVE_ROW_DIMENSION = nombre de lignes invalide : {0} (doit \u00eatre positif)
NOT_POSITIVE_SAMPLE_SIZE = la taille de l''\u00e9chantillon doit \u00eatre positive ({0}) NOT_POSITIVE_SAMPLE_SIZE = la taille de l''\u00e9chantillon doit \u00eatre positive ({0})
NOT_POSITIVE_SCALE = l''\u00e9chelle doit \u00eatre positive ({0}) NOT_POSITIVE_SCALE = l''\u00e9chelle doit \u00eatre positive ({0})

View File

@ -52,6 +52,10 @@ The <action> type attribute can be add,update,fix,remove.
If the output is not quite correct, check for invisible trailing spaces! If the output is not quite correct, check for invisible trailing spaces!
--> -->
<release version="3.0" date="TBD" description="TBD"> <release version="3.0" date="TBD" description="TBD">
<action dev="erans" type="update" issue="MATH-310">
Made "sample" methods part of the "IntegerDistribution" and
"ContinuousDistribution" interfaces.
</action>
<action dev="erans" type="fix" issue="MATH-349"> <action dev="erans" type="fix" issue="MATH-349">
All distribution classes (in package "distribution") are immutable. All distribution classes (in package "distribution") are immutable.
</action> </action>

View File

@ -18,6 +18,9 @@
package org.apache.commons.math.distribution; package org.apache.commons.math.distribution;
import org.apache.commons.math.TestUtils; import org.apache.commons.math.TestUtils;
import org.apache.commons.math.exception.NotPositiveException;
import org.apache.commons.math.exception.NotStrictlyPositiveException;
import org.apache.commons.math.exception.NumberIsTooLargeException;
/** /**
* Test cases for HyperGeometriclDistribution. * Test cases for HyperGeometriclDistribution.
@ -127,16 +130,45 @@ public class HypergeometricDistributionTest extends IntegerDistributionAbstractT
verifyInverseCumulativeProbabilities(); verifyInverseCumulativeProbabilities();
} }
public void testPopulationSize() { public void testPreconditions() {
HypergeometricDistribution dist = new HypergeometricDistributionImpl(5,3,5); HypergeometricDistribution dist;
try { try {
dist.setPopulationSize(-1); dist = new HypergeometricDistributionImpl(0, 3, 5);
fail("negative population size. IllegalArgumentException expected"); fail("negative population size. NotStrictlyPositiveException expected");
} catch(IllegalArgumentException ex) { } catch(NotStrictlyPositiveException ex) {
// Expected.
} }
try {
dist = new HypergeometricDistributionImpl(5, -1, 5);
fail("negative number of successes. NotPositiveException expected");
} catch(NotPositiveException ex) {
// Expected.
}
try {
dist = new HypergeometricDistributionImpl(5, 3, -1);
fail("negative sample size. NotPositiveException expected");
} catch(NotPositiveException ex) {
// Expected.
}
try {
dist = new HypergeometricDistributionImpl(5, 6, 5);
fail("numberOfSuccesses > populationSize. NumberIsTooLargeException expected");
} catch(NumberIsTooLargeException ex) {
// Expected.
}
try {
dist = new HypergeometricDistributionImpl(5, 3, 6);
fail("sampleSize > populationSize. NumberIsTooLargeException expected");
} catch(NumberIsTooLargeException ex) {
// Expected.
}
}
dist.setPopulationSize(10); public void testAccessors() {
assertEquals(10, dist.getPopulationSize()); HypergeometricDistribution dist = new HypergeometricDistributionImpl(5, 3, 4);
assertEquals(5, dist.getPopulationSize());
assertEquals(3, dist.getNumberOfSuccesses());
assertEquals(4, dist.getSampleSize());
} }
public void testLargeValues() { public void testLargeValues() {

View File

@ -17,6 +17,8 @@
package org.apache.commons.math.distribution; package org.apache.commons.math.distribution;
import org.apache.commons.math.exception.NotStrictlyPositiveException;
/** /**
* Test cases for {@link ZipfDistribution}. * Test cases for {@link ZipfDistribution}.
* Extends IntegerDistributionAbstractTest. See class javadoc for * Extends IntegerDistributionAbstractTest. See class javadoc for
@ -29,6 +31,22 @@ public class ZipfDistributionTest extends IntegerDistributionAbstractTest {
super(name); super(name);
} }
public void testPreconditions() {
ZipfDistribution dist;
try {
dist = new ZipfDistributionImpl(0, 1);
fail("NotStrictlyPositiveException expected");
} catch (NotStrictlyPositiveException e) {
// Expected.
}
try {
dist = new ZipfDistributionImpl(1, 0);
fail("NotStrictlyPositiveException expected");
} catch (NotStrictlyPositiveException e) {
// Expected.
}
}
//-------------- Implementations for abstract methods ----------------------- //-------------- Implementations for abstract methods -----------------------
/** Creates the default discrete distribution instance to use in tests. */ /** Creates the default discrete distribution instance to use in tests. */