diff --git a/src/main/java/org/apache/commons/math/distribution/UniformIntegerDistribution.java b/src/main/java/org/apache/commons/math/distribution/UniformIntegerDistribution.java new file mode 100644 index 000000000..a6dd99a70 --- /dev/null +++ b/src/main/java/org/apache/commons/math/distribution/UniformIntegerDistribution.java @@ -0,0 +1,140 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.math.distribution; + +import org.apache.commons.math.exception.NumberIsTooLargeException; +import org.apache.commons.math.exception.util.LocalizedFormats; + +/** + * Implementation of the uniform integer distribution. + * + * @see Uniform distribution (discrete), at Wikipedia + * + * @version $Id$ + * @since 3.0 + */ +public class UniformIntegerDistribution extends AbstractIntegerDistribution { + /** Serializable version identifier. */ + private static final long serialVersionUID = 20120109L; + + /** Lower bound (inclusive) of this distribution. */ + private final int lower; + + /** Upper bound (inclusive) of this distribution. */ + private final int upper; + + /** + * Creates a new uniform integer distribution using the given lower and + * upper bounds (both inclusive). + * + * @param lower Lower bound (inclusive) of this distribution. + * @param upper Upper bound (inclusive) of this distribution. + * @throws NumberIsTooLargeException if {@code lower >= upper}. + */ + public UniformIntegerDistribution(int lower, int upper) throws NumberIsTooLargeException { + if (lower >= upper) { + throw new NumberIsTooLargeException( + LocalizedFormats.LOWER_BOUND_NOT_BELOW_UPPER_BOUND, + lower, upper, false); + } + this.lower = lower; + this.upper = upper; + } + + /** {@inheritDoc} */ + public double probability(int x) { + if (x < lower || x > upper) { + return 0; + } + return 1.0 / (upper - lower + 1); + } + + /** {@inheritDoc} */ + public double cumulativeProbability(int x) { + if (x < lower) { + return 0; + } + if (x > upper) { + return 1; + } + return (x - lower + 1.0) / (upper - lower + 1.0); + } + + /** + * {@inheritDoc} + * + * For lower bound {@code lower} and upper bound {@code upper}, the mean is + * {@code 0.5 * (lower + upper)}. + */ + public double getNumericalMean() { + return 0.5 * (lower + upper); + } + + /** + * {@inheritDoc} + * + * For lower bound {@code lower} and upper bound {@code upper}, and + * {@code n = upper - lower + 1}, the variance is {@code (n^2 - 1) / 12}. + */ + public double getNumericalVariance() { + double n = upper - lower + 1; + return (n * n - 1) / 12.0; + } + + /** + * {@inheritDoc} + * + * The lower bound of the support is equal to the lower bound parameter + * of the distribution. + * + * @return lower bound of the support + */ + public int getSupportLowerBound() { + return lower; + } + + /** + * {@inheritDoc} + * + * The upper bound of the support is equal to the upper bound parameter + * of the distribution. + * + * @return upper bound of the support + */ + public int getSupportUpperBound() { + return upper; + } + + /** + * {@inheritDoc} + * + * The support of this distribution is connected. + * + * @return {@code true} + */ + public boolean isSupportConnected() { + return true; + } + + /** {@inheritDoc} */ + @Override + public int sample() { + return randomData.nextInt(lower, upper); + } +} diff --git a/src/main/java/org/apache/commons/math/distribution/UniformRealDistribution.java b/src/main/java/org/apache/commons/math/distribution/UniformRealDistribution.java new file mode 100644 index 000000000..896389ae2 --- /dev/null +++ b/src/main/java/org/apache/commons/math/distribution/UniformRealDistribution.java @@ -0,0 +1,198 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.math.distribution; + +import org.apache.commons.math.exception.NumberIsTooLargeException; +import org.apache.commons.math.exception.util.LocalizedFormats; + +/** + * Implementation of the uniform real distribution. + * + * @see Uniform distribution (continuous), at Wikipedia + * + * @version $Id$ + * @since 3.0 + */ +public class UniformRealDistribution extends AbstractRealDistribution { + /** Default inverse cumulative probability accuracy. */ + public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9; + + /** Serializable version identifier. */ + private static final long serialVersionUID = 20120109L; + + /** Lower bound of this distribution (inclusive). */ + private final double lower; + + /** Upper bound of this distribution (exclusive). */ + private final double upper; + + /** Inverse cumulative probability accuracy. */ + private final double solverAbsoluteAccuracy; + + /** + * Create a uniform real distribution using the given lower and upper + * bounds. + * + * @param lower Lower bound of this distribution (inclusive). + * @param upper Upper bound of this distribution (exclusive). + * @throws NumberIsTooLargeException if {@code lower >= upper}. + */ + public UniformRealDistribution(double lower, double upper) + throws NumberIsTooLargeException { + this(lower, upper, DEFAULT_INVERSE_ABSOLUTE_ACCURACY); + } + + /** + * Create a normal distribution using the given mean, standard deviation and + * inverse cumulative distribution accuracy. + * + * @param lower Lower bound of this distribution (inclusive). + * @param upper Upper bound of this distribution (exclusive). + * @param inverseCumAccuracy Inverse cumulative probability accuracy. + * @throws NumberIsTooLargeException if {@code lower >= upper}. + */ + public UniformRealDistribution(double lower, double upper, double inverseCumAccuracy) + throws NumberIsTooLargeException { + if (lower >= upper) { + throw new NumberIsTooLargeException( + LocalizedFormats.LOWER_BOUND_NOT_BELOW_UPPER_BOUND, + lower, upper, false); + } + + this.lower = lower; + this.upper = upper; + solverAbsoluteAccuracy = inverseCumAccuracy; + } + + /** + * Create a standard uniform real distribution with lower bound (inclusive) + * equal to zero and upper bound (exclusive) equal to one. + */ + public UniformRealDistribution() { + this(0, 1); + } + + /** + * {@inheritDoc} + * + * For this distribution {@code P(X = x)} always evaluates to 0. + * + * @return 0 + */ + public double probability(double x) { + return 0.0; + } + + /** {@inheritDoc} */ + public double density(double x) { + if (x < lower || x > upper) { + return 0.0; + } + return 1 / (upper - lower); + } + + /** {@inheritDoc} */ + public double cumulativeProbability(double x) { + if (x <= lower) { + return 0; + } + if (x >= upper) { + return 1; + } + return (x - lower) / (upper - lower); + } + + /** {@inheritDoc} */ + @Override + protected double getSolverAbsoluteAccuracy() { + return solverAbsoluteAccuracy; + } + + /** + * {@inheritDoc} + * + * For lower bound {@code lower} and upper bound {@code upper}, the mean is + * {@code 0.5 * (lower + upper)}. + */ + public double getNumericalMean() { + return 0.5 * (lower + upper); + } + + /** + * {@inheritDoc} + * + * For lower bound {@code lower} and upper bound {@code upper}, the + * variance is {@code (upper - lower)^2 / 12}. + */ + public double getNumericalVariance() { + double ul = upper - lower; + return ul * ul / 12; + } + + /** + * {@inheritDoc} + * + * The lower bound of the support is equal to the lower bound parameter + * of the distribution. + * + * @return lower bound of the support + */ + public double getSupportLowerBound() { + return lower; + } + + /** + * {@inheritDoc} + * + * The upper bound of the support is equal to the upper bound parameter + * of the distribution. + * + * @return upper bound of the support + */ + public double getSupportUpperBound() { + return upper; + } + + /** {@inheritDoc} */ + public boolean isSupportLowerBoundInclusive() { + return true; + } + + /** {@inheritDoc} */ + public boolean isSupportUpperBoundInclusive() { + return false; + } + + /** + * {@inheritDoc} + * + * The support of this distribution is connected. + * + * @return {@code true} + */ + public boolean isSupportConnected() { + return true; + } + + /** {@inheritDoc} */ + @Override + public double sample() { + return randomData.nextUniform(lower, upper, true); + } +} diff --git a/src/main/java/org/apache/commons/math/random/RandomData.java b/src/main/java/org/apache/commons/math/random/RandomData.java index 80cb93aa5..976b97804 100644 --- a/src/main/java/org/apache/commons/math/random/RandomData.java +++ b/src/main/java/org/apache/commons/math/random/RandomData.java @@ -203,7 +203,7 @@ public interface RandomData { /** * Generates a uniformly distributed random value from the open interval - * (lower,upper) (i.e., endpoints excluded). + * {@code (lower, upper)} (i.e., endpoints excluded). *

* Definition: * @@ -211,11 +211,6 @@ public interface RandomData { * upper - lower are the * * location and scale parameters, respectively.

- *

- * Preconditions:

* * @param lower lower endpoint of the interval of support * @param upper upper endpoint of the interval of support @@ -224,6 +219,29 @@ public interface RandomData { */ double nextUniform(double lower, double upper); + /** + * Generates a uniformly distributed random value from the interval + * {@code (lower, upper)} or the interval {@code [lower, upper)}. The lower + * bound is thus optionally included, while the upper bound is always + * excluded. + *

+ * Definition: + * + * Uniform Distribution lower and + * upper - lower are the + * + * location and scale parameters, respectively.

+ * + * @param lower lower endpoint of the interval of support + * @param upper upper endpoint of the interval of support + * @param lowerInclusive {@code true} if the lower bound is included in the + * interval + * @return uniformly distributed random value in the {@code (lower, upper)} + * interval, if {@code lowerInclusive} is {@code false}, or in the + * {@code [lower, upper)} interval, if {@code lowerInclusive} is {@code true} + */ + double nextUniform(double lower, double upper, boolean lowerInclusive); + /** * Generates an integer array of length k whose entries * are selected randomly, without repetition, from the integers diff --git a/src/main/java/org/apache/commons/math/random/RandomDataImpl.java b/src/main/java/org/apache/commons/math/random/RandomDataImpl.java index 78e883518..f47c38f86 100644 --- a/src/main/java/org/apache/commons/math/random/RandomDataImpl.java +++ b/src/main/java/org/apache/commons/math/random/RandomDataImpl.java @@ -593,9 +593,34 @@ public class RandomDataImpl implements RandomData, Serializable { * or either bound is infinite or NaN */ public double nextUniform(double lower, double upper) { + return nextUniform(lower, upper, false); + } + + /** + * {@inheritDoc} + *

+ * Algorithm Description: if the lower bound is excluded, + * scales the output of Random.nextDouble(), but rejects 0 values (i.e., + * will generate another random double if Random.nextDouble() returns 0). + * This is necessary to provide a symmetric output interval (both + * endpoints excluded). + *

+ * + * @param lower + * the lower bound. + * @param upper + * the upper bound. + * @param lowerInclusive + * whether the lower bound is included in the interval + * @return a uniformly distributed random value from the interval (lower, + * upper) + * @throws NumberIsTooLargeException if {@code lower >= upper}. + * @since 3.0 + */ + public double nextUniform(double lower, double upper, boolean lowerInclusive) { if (lower >= upper) { - throw new MathIllegalArgumentException(LocalizedFormats.LOWER_BOUND_NOT_BELOW_UPPER_BOUND, - lower, upper); + throw new NumberIsTooLargeException(LocalizedFormats.LOWER_BOUND_NOT_BELOW_UPPER_BOUND, + lower, upper, false); } if (Double.isInfinite(lower) || Double.isInfinite(upper)) { @@ -610,7 +635,7 @@ public class RandomDataImpl implements RandomData, Serializable { // ensure nextDouble() isn't 0.0 double u = generator.nextDouble(); - while (u <= 0.0) { + while (!lowerInclusive && u <= 0.0) { u = generator.nextDouble(); } diff --git a/src/test/java/org/apache/commons/math/distribution/UniformIntegerDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/UniformIntegerDistributionTest.java new file mode 100644 index 000000000..a828df918 --- /dev/null +++ b/src/test/java/org/apache/commons/math/distribution/UniformIntegerDistributionTest.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.math.distribution; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Test cases for UniformIntegerDistribution. See class javadoc for + * {@link IntegerDistributionAbstractTest} for further details. + */ +public class UniformIntegerDistributionTest extends IntegerDistributionAbstractTest { + + // --- Override tolerance ------------------------------------------------- + + @Override + public void setUp() { + super.setUp(); + setTolerance(1e-9); + } + + //--- Implementations for abstract methods -------------------------------- + + /** Creates the default discrete distribution instance to use in tests. */ + @Override + public IntegerDistribution makeDistribution() { + return new UniformIntegerDistribution(-3, 5); + } + + /** Creates the default probability density test input values. */ + @Override + public int[] makeDensityTestPoints() { + return new int[] {-4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6}; + } + + /** Creates the default probability density test expected values. */ + @Override + public double[] makeDensityTestValues() { + double d = 1.0 / (5 - -3 + 1); + return new double[] {0, d, d, d, d, d, d, d, d, d, 0}; + } + + /** Creates the default cumulative probability density test input values. */ + @Override + public int[] makeCumulativeTestPoints() { + return makeDensityTestPoints(); + } + + /** Creates the default cumulative probability density test expected values. */ + @Override + public double[] makeCumulativeTestValues() { + return new double[] {0, 1 / 9.0, 2 / 9.0, 3 / 9.0, 4 / 9.0, 5 / 9.0, + 6 / 9.0, 7 / 9.0, 8 / 9.0, 1, 1}; + } + + /** Creates the default inverse cumulative probability test input values */ + @Override + public double[] makeInverseCumulativeTestPoints() { + return new double[] {0, 0.001, 0.010, 0.025, 0.050, 0.100, 0.200, + 0.5, 0.999, 0.990, 0.975, 0.950, 0.900, 1}; + } + + /** Creates the default inverse cumulative probability density test expected values */ + @Override + public int[] makeInverseCumulativeTestValues() { + return new int[] {-3, -3, -3, -3, -3, -3, -2, 1, 5, 5, 5, 5, 5, 5}; + } + + //--- Additional test cases ----------------------------------------------- + + /** Test mean/variance. */ + @Test + public void testMoments() { + UniformIntegerDistribution dist; + + dist = new UniformIntegerDistribution(0, 5); + Assert.assertEquals(dist.getNumericalMean(), 2.5, 0); + Assert.assertEquals(dist.getNumericalVariance(), 35 / 12.0, 0); + + dist = new UniformIntegerDistribution(0, 1); + Assert.assertEquals(dist.getNumericalMean(), 0.5, 0); + Assert.assertEquals(dist.getNumericalVariance(), 3 / 12.0, 0); + } +} diff --git a/src/test/java/org/apache/commons/math/distribution/UniformRealDistributionTest.java b/src/test/java/org/apache/commons/math/distribution/UniformRealDistributionTest.java new file mode 100644 index 000000000..821e05c18 --- /dev/null +++ b/src/test/java/org/apache/commons/math/distribution/UniformRealDistributionTest.java @@ -0,0 +1,113 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.math.distribution; + +import org.apache.commons.math.exception.NumberIsTooLargeException; +import org.junit.Assert; +import org.junit.Test; + +/** + * Test cases for UniformRealDistribution. See class javadoc for + * {@link RealDistributionAbstractTest} for further details. + */ +public class UniformRealDistributionTest extends RealDistributionAbstractTest { + + // --- Override tolerance ------------------------------------------------- + + @Override + public void setUp() throws Exception { + super.setUp(); + setTolerance(1e-4); + } + + //--- Implementations for abstract methods -------------------------------- + + /** Creates the default uniform real distribution instance to use in tests. */ + @Override + public UniformRealDistribution makeDistribution() { + return new UniformRealDistribution(-0.5, 1.25); + } + + /** Creates the default cumulative probability distribution test input values */ + @Override + public double[] makeCumulativeTestPoints() { + return new double[] {-0.5001, -0.5, -0.4999, -0.25, -0.0001, 0.0, + 0.0001, 0.25, 1.0, 1.2499, 1.25, 1.2501}; + } + + /** Creates the default cumulative probability density test expected values */ + @Override + public double[] makeCumulativeTestValues() { + return new double[] {0.0, 0.0, 0.0001, 0.25/1.75, 0.4999/1.75, + 0.5/1.75, 0.5001/1.75, 0.75/1.75, 1.5/1.75, + 1.7499/1.75, 1.0, 1.0}; + } + + /** Creates the default probability density test expected values */ + @Override + public double[] makeDensityTestValues() { + double d = 1 / 1.75; + return new double[] {0, d, d, d, d, d, d, d, d, d, d, 0}; + } + + //--- Additional test cases ----------------------------------------------- + + /** Test lower bound getter. */ + @Test + public void testGetLowerBound() { + UniformRealDistribution distribution = makeDistribution(); + Assert.assertEquals(-0.5, distribution.getSupportLowerBound(), 0); + } + + /** Test upper bound getter. */ + @Test + public void testGetUpperBound() { + UniformRealDistribution distribution = makeDistribution(); + Assert.assertEquals(1.25, distribution.getSupportUpperBound(), 0); + } + + /** Test pre-condition for equal lower/upper bound. */ + @Test(expected=NumberIsTooLargeException.class) + public void testPreconditions1() { + new UniformRealDistribution(0, 0); + } + + /** Test pre-condition for lower bound larger than upper bound. */ + @Test(expected=NumberIsTooLargeException.class) + public void testPreconditions2() { + new UniformRealDistribution(1, 0); + } + + /** Test mean/variance. */ + @Test + public void testMeanVariance() { + UniformRealDistribution dist; + + dist = new UniformRealDistribution(0, 1); + Assert.assertEquals(dist.getNumericalMean(), 0.5, 0); + Assert.assertEquals(dist.getNumericalVariance(), 1/12.0, 0); + + dist = new UniformRealDistribution(-1.5, 0.6); + Assert.assertEquals(dist.getNumericalMean(), -0.45, 0); + Assert.assertEquals(dist.getNumericalVariance(), 0.3675, 0); + + dist = new UniformRealDistribution(-0.5, 1.25); + Assert.assertEquals(dist.getNumericalMean(), 0.375, 0); + Assert.assertEquals(dist.getNumericalVariance(), 0.2552083333333333, 0); + } +}