UniformIntegerDistribution.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.math3.distribution;

  18. import org.apache.commons.math3.exception.NumberIsTooLargeException;
  19. import org.apache.commons.math3.exception.util.LocalizedFormats;
  20. import org.apache.commons.math3.random.RandomGenerator;
  21. import org.apache.commons.math3.random.Well19937c;

  22. /**
  23.  * Implementation of the uniform integer distribution.
  24.  *
  25.  * @see <a href="http://en.wikipedia.org/wiki/Uniform_distribution_(discrete)"
  26.  * >Uniform distribution (discrete), at Wikipedia</a>
  27.  *
  28.  * @since 3.0
  29.  */
  30. public class UniformIntegerDistribution extends AbstractIntegerDistribution {
  31.     /** Serializable version identifier. */
  32.     private static final long serialVersionUID = 20120109L;
  33.     /** Lower bound (inclusive) of this distribution. */
  34.     private final int lower;
  35.     /** Upper bound (inclusive) of this distribution. */
  36.     private final int upper;

  37.     /**
  38.      * Creates a new uniform integer distribution using the given lower and
  39.      * upper bounds (both inclusive).
  40.      * <p>
  41.      * <b>Note:</b> this constructor will implicitly create an instance of
  42.      * {@link Well19937c} as random generator to be used for sampling only (see
  43.      * {@link #sample()} and {@link #sample(int)}). In case no sampling is
  44.      * needed for the created distribution, it is advised to pass {@code null}
  45.      * as random generator via the appropriate constructors to avoid the
  46.      * additional initialisation overhead.
  47.      *
  48.      * @param lower Lower bound (inclusive) of this distribution.
  49.      * @param upper Upper bound (inclusive) of this distribution.
  50.      * @throws NumberIsTooLargeException if {@code lower >= upper}.
  51.      */
  52.     public UniformIntegerDistribution(int lower, int upper)
  53.         throws NumberIsTooLargeException {
  54.         this(new Well19937c(), lower, upper);
  55.     }

  56.     /**
  57.      * Creates a new uniform integer distribution using the given lower and
  58.      * upper bounds (both inclusive).
  59.      *
  60.      * @param rng Random number generator.
  61.      * @param lower Lower bound (inclusive) of this distribution.
  62.      * @param upper Upper bound (inclusive) of this distribution.
  63.      * @throws NumberIsTooLargeException if {@code lower > upper}.
  64.      * @since 3.1
  65.      */
  66.     public UniformIntegerDistribution(RandomGenerator rng,
  67.                                       int lower,
  68.                                       int upper)
  69.         throws NumberIsTooLargeException {
  70.         super(rng);

  71.         if (lower > upper) {
  72.             throw new NumberIsTooLargeException(
  73.                             LocalizedFormats.LOWER_BOUND_NOT_BELOW_UPPER_BOUND,
  74.                             lower, upper, true);
  75.         }
  76.         this.lower = lower;
  77.         this.upper = upper;
  78.     }

  79.     /** {@inheritDoc} */
  80.     public double probability(int x) {
  81.         if (x < lower || x > upper) {
  82.             return 0;
  83.         }
  84.         return 1.0 / (upper - lower + 1);
  85.     }

  86.     /** {@inheritDoc} */
  87.     public double cumulativeProbability(int x) {
  88.         if (x < lower) {
  89.             return 0;
  90.         }
  91.         if (x > upper) {
  92.             return 1;
  93.         }
  94.         return (x - lower + 1.0) / (upper - lower + 1.0);
  95.     }

  96.     /**
  97.      * {@inheritDoc}
  98.      *
  99.      * For lower bound {@code lower} and upper bound {@code upper}, the mean is
  100.      * {@code 0.5 * (lower + upper)}.
  101.      */
  102.     public double getNumericalMean() {
  103.         return 0.5 * (lower + upper);
  104.     }

  105.     /**
  106.      * {@inheritDoc}
  107.      *
  108.      * For lower bound {@code lower} and upper bound {@code upper}, and
  109.      * {@code n = upper - lower + 1}, the variance is {@code (n^2 - 1) / 12}.
  110.      */
  111.     public double getNumericalVariance() {
  112.         double n = upper - lower + 1;
  113.         return (n * n - 1) / 12.0;
  114.     }

  115.     /**
  116.      * {@inheritDoc}
  117.      *
  118.      * The lower bound of the support is equal to the lower bound parameter
  119.      * of the distribution.
  120.      *
  121.      * @return lower bound of the support
  122.      */
  123.     public int getSupportLowerBound() {
  124.         return lower;
  125.     }

  126.     /**
  127.      * {@inheritDoc}
  128.      *
  129.      * The upper bound of the support is equal to the upper bound parameter
  130.      * of the distribution.
  131.      *
  132.      * @return upper bound of the support
  133.      */
  134.     public int getSupportUpperBound() {
  135.         return upper;
  136.     }

  137.     /**
  138.      * {@inheritDoc}
  139.      *
  140.      * The support of this distribution is connected.
  141.      *
  142.      * @return {@code true}
  143.      */
  144.     public boolean isSupportConnected() {
  145.         return true;
  146.     }

  147.     /** {@inheritDoc} */
  148.     @Override
  149.     public int sample() {
  150.         final int max = (upper - lower) + 1;
  151.         if (max <= 0) {
  152.             // The range is too wide to fit in a positive int (larger
  153.             // than 2^31); as it covers more than half the integer range,
  154.             // we use a simple rejection method.
  155.             while (true) {
  156.                 final int r = random.nextInt();
  157.                 if (r >= lower &&
  158.                     r <= upper) {
  159.                     return r;
  160.                 }
  161.             }
  162.         } else {
  163.             // We can shift the range and directly generate a positive int.
  164.             return lower + random.nextInt(max);
  165.         }
  166.     }
  167. }