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 18 package org.apache.commons.rng.sampling.distribution; 19 20 import org.apache.commons.rng.UniformRandomProvider; 21 22 /** 23 * Discrete uniform distribution sampler. 24 */ 25 public class DiscreteUniformSampler 26 extends SamplerBase 27 implements DiscreteSampler { 28 /** Lower bound. */ 29 private final int lower; 30 /** Upper bound. */ 31 private final int upper; 32 /** Underlying source of randomness. */ 33 private final UniformRandomProvider rng; 34 35 /** 36 * @param rng Generator of uniformly distributed random numbers. 37 * @param lower Lower bound (inclusive) of the distribution. 38 * @param upper Upper bound (inclusive) of the distribution. 39 * @throws IllegalArgumentException if {@code lower > upper}. 40 */ 41 public DiscreteUniformSampler(UniformRandomProvider rng, 42 int lower, 43 int upper) { 44 super(null); 45 this.rng = rng; 46 if (lower > upper) { 47 throw new IllegalArgumentException(lower + " > " + upper); 48 } 49 50 this.lower = lower; 51 this.upper = upper; 52 } 53 54 /** {@inheritDoc} */ 55 @Override 56 public int sample() { 57 final int max = (upper - lower) + 1; 58 if (max <= 0) { 59 // The range is too wide to fit in a positive int (larger 60 // than 2^31); as it covers more than half the integer range, 61 // we use a simple rejection method. 62 while (true) { 63 final int r = rng.nextInt(); 64 if (r >= lower && 65 r <= upper) { 66 return r; 67 } 68 } 69 } else { 70 // We can shift the range and directly generate a positive int. 71 return lower + rng.nextInt(max); 72 } 73 } 74 75 /** {@inheritDoc} */ 76 @Override 77 public String toString() { 78 return "Uniform deviate [" + rng.toString() + "]"; 79 } 80 }