ExponentialDistribution.hpp
Go to the documentation of this file.
00001 /**
00002  * \file ExponentialDistribution.hpp
00003  * \brief Header for ExponentialDistribution
00004  *
00005  * Sample from an exponential distribution.
00006  *
00007  * Written by Charles Karney <charles@karney.com> and licensed under the LGPL.
00008  * For more information, see http://randomlib.sourceforge.net/
00009  **********************************************************************/
00010 
00011 #if !defined(EXPONENTIALDISTRIBUTION_HPP)
00012 #define EXPONENTIALDISTRIBUTION_HPP "$Id: ExponentialDistribution.hpp 6723 2010-01-11 14:20:10Z ckarney $"
00013 
00014 #include <cmath>
00015 
00016 namespace RandomLib {
00017   /**
00018    * \brief The exponential distribution.
00019    *
00020    * Sample from the distribution exp(-\e x) for \e x >= 0.  This uses the
00021    * logarithm method, see Knuth, TAOCP, Vol 2, Sec 3.4.1.D.  Example
00022    * \code
00023    *   #include "RandomLib/ExponentialDistribution.hpp"
00024    *
00025    *   RandomLib::Random r;
00026    *   std::cout << "Seed set to " << r.SeedString() << std::endl;
00027    *   RandomLib::ExponentialDistribution<double> expdist;
00028    *   std::cout << "Select from exponential distribution:";
00029    *   for (size_t i = 0; i < 10; ++i)
00030    *       std::cout << " " << expdist(r);
00031    *   std::cout << std::endl;
00032    * \endcode
00033    **********************************************************************/
00034   template<typename RealType = double> class ExponentialDistribution {
00035   public:
00036     /**
00037      * The type returned by ExponentialDistribution::operator()(Random&)
00038      **********************************************************************/
00039     typedef RealType result_type;
00040     /**
00041      * Return a sample of type RealType from the exponential distribution and
00042      * mean \a mu.  This uses Random::FloatU() which avoids taking log(0) and
00043      * allows rare large values to be returned.  If \a mu = 1, minimum returned
00044      * value = 0 with prob 1/2<sup><i>p</i></sup>; maximum returned value =
00045      * log(2)(\e p + \e e) with prob 1/2<sup><i>p</i> + <i>e</i></sup>.  Here
00046      * \e p is the precision of real type RealType and \e e is the exponent
00047      * range.
00048      **********************************************************************/
00049     template<class Random>
00050     RealType operator()(Random& r, RealType mu = RealType(1)) const throw();
00051   };
00052 
00053   template<typename RealType>  template<class Random> inline RealType
00054   ExponentialDistribution<RealType>::operator()(Random& r, RealType mu) const
00055     throw() {
00056     return -mu * std::log(r.template FloatU<RealType>());
00057   }
00058 } // namespace RandomLib
00059 #endif // EXPONENTIALDISTRIBUTION_HPP