aimstil  5.0.5
proba_distributions.tpp
Go to the documentation of this file.
1 #ifndef PROBA_DISTRIBUTIONS_TPP_
2 #define PROBA_DISTRIBUTIONS_TPP_
3 
4 // includes from STL
5 #include <cassert>
6 #include <cstdlib> // std::rand
7 #include <limits>
8 
9 namespace til
10 {
11 
12  //---------------------------------------------------------------------------
13 
14  template < typename T >
15  UniformRandomDistribution<T>::UniformRandomDistribution(T min, T max)
16  : m_min(min)
17  , m_max(max)
18  { assert(min <= max); }
19 
20  //---------------------------------------------------------------------------
21 
22  template < typename T >
23  T UniformRandomDistribution<T>::operator()()
24  {
25  if (std::numeric_limits<T>::is_integer)
26  {
27  // Epsilon correspond to the safety margin we want on the side of the
28  // continuous uniform distribution, to be sure that when rounding we
29  // never get min-1 or max+1
30  // NB: with epsilon == 0 , I once obtained max+1 !!
31  // TODO: is this much better / efficient than two tests (on min and max)?
32  const double eps = 32 * std::numeric_limits<double>::epsilon();
33  T res = castValue<double, T>(std::rand() / double(RAND_MAX) * (m_max - m_min + 1 - 2*eps) + m_min - 0.5 + eps);
34  assert(res >= m_min);
35  assert(res <= m_max);
36  return res;
37  }
38  else
39  {
40  // TODO: is there the same issue here as above?
41  T res = castValue<double, T>(std::rand() / double(RAND_MAX) * (m_max - m_min) + m_min);
42  assert(res >= m_min);
43  assert(res <= m_max);
44  return res;
45  }
46  }
47 
48  //---------------------------------------------------------------------------
49 
50  template < typename T >
51  T rand(T min, T max)
52  {
53  UniformRandomDistribution<T> u(min, max);
54  return u();
55  }
56 
57  //---------------------------------------------------------------------------
58 
59 } // namespace til
60 
61 #endif /*PROBA_DISTRIBUTIONS_TPP_*/