001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.rng.sampling.distribution; 018 019import org.apache.commons.rng.UniformRandomProvider; 020 021/** 022 * Sampling from a uniform distribution. 023 * 024 * @since 1.0 025 */ 026public class ContinuousUniformSampler 027 extends SamplerBase 028 implements ContinuousSampler { 029 /** Lower bound. */ 030 private final double lo; 031 /** Higher bound. */ 032 private final double hi; 033 /** Underlying source of randomness. */ 034 private final UniformRandomProvider rng; 035 036 /** 037 * @param rng Generator of uniformly distributed random numbers. 038 * @param lo Lower bound. 039 * @param hi Higher bound. 040 */ 041 public ContinuousUniformSampler(UniformRandomProvider rng, 042 double lo, 043 double hi) { 044 super(null); 045 this.rng = rng; 046 this.lo = lo; 047 this.hi = hi; 048 } 049 050 /** {@inheritDoc} */ 051 @Override 052 public double sample() { 053 final double u = rng.nextDouble(); 054 return u * hi + (1 - u) * lo; 055 } 056 057 /** {@inheritDoc} */ 058 @Override 059 public String toString() { 060 return "Uniform deviate [" + rng.toString() + "]"; 061 } 062}