DUniform.h

00001 /*  _________________________________________________________________________
00002  *
00003  *  UTILIB: A utility library for developing portable C++ codes.
00004  *  Copyright (c) 2001, Sandia National Laboratories.
00005  *  This software is distributed under the GNU Lesser General Public License.
00006  *  For more information, see the README file in the top UTILIB directory.
00007  *  _________________________________________________________________________
00008  */
00009 
00010 //
00011 // DUniform.h
00012 //
00019 #ifndef __DUniform_h
00020 #define __DUniform_h
00021 
00022 #ifndef ANSI_HDRS
00023 #include <math.h>
00024 #else
00025 #include <cmath>
00026 #endif
00027 #include "DRandVar.h"
00028 
00029 
00030 class UTILIB_API DUniform: public DRandVar {
00031 
00032 public:
00033 
00035     DUniform(RNG *gen=(RNG*)NULL, int low=0, int high=1);
00036 
00038     int low();
00040     int low(int x);
00042     int high();
00044     int high(int x);
00045 
00047     virtual int operator()();
00049     int operator()(int low_, int high_);
00050 
00051 protected:
00052 
00054     int pLow;
00056     int pHigh;
00058     int delta;
00059 
00060 };
00061 
00062 
00063 inline DUniform::DUniform(RNG *gen, int low, int high)
00064 :DRandVar(gen)
00065 {
00066     pLow = (low < high) ? low : high;
00067     pHigh = (low < high) ? high : low;
00068     delta = pHigh - pLow;
00069 }
00070 
00071 inline int DUniform::low() { return pLow; }
00072 
00073 inline int DUniform::low(int x) {
00074   int tmp = pLow;
00075   pLow = x;
00076   delta = pHigh - pLow;
00077   return tmp;
00078 }
00079 
00080 inline int DUniform::high() { return pHigh; }
00081 
00082 inline int DUniform::high(int x) {
00083   int tmp = pHigh;
00084   pHigh = x;
00085   delta = pHigh - pLow;
00086   return tmp;
00087 }
00088 
00089 
00090 inline int DUniform::operator()(int low_, int high_)
00091 {
00092 low(low_);
00093 high(high_);
00094 return (*this)();
00095 }
00096 
00097 
00098 inline int DUniform::operator()()
00099 {
00100 RNG* rng;
00101 
00102 if ((rng = generator()) == NULL) {
00103    ErrReturn("DUniform::operator() : Attempting to use a NULL RNG.");
00104    }
00105 else {
00106    int temp = (int)floor(pLow + (pHigh-pLow+1) * rng->asDouble());
00107    if (temp > pHigh)
00108       temp = pHigh;             // This handles the case when urand == 1.0
00109    return(temp);
00110    }
00111 }
00112 
00113 #endif