1 /* boost random/generate_canonical.hpp header file
3 * Copyright Steven Watanabe 2011
4 * Distributed under the Boost Software License, Version 1.0. (See
5 * accompanying file LICENSE_1_0.txt or copy at
6 * http://www.boost.org/LICENSE_1_0.txt)
8 * See http://www.boost.org for most recent version including documentation.
10 * $Id: generate_canonical.hpp 72951 2011-07-07 04:57:37Z steven_watanabe $
14 #ifndef BOOST_RANDOM_GENERATE_CANONICAL_HPP
15 #define BOOST_RANDOM_GENERATE_CANONICAL_HPP
18 #include <boost/assert.hpp>
19 #include <boost/config/no_tr1/cmath.hpp>
20 #include <boost/limits.hpp>
21 #include <boost/type_traits/is_integral.hpp>
22 #include <boost/math/special_functions.hpp>
23 #include <boost/random/detail/signed_unsigned_tools.hpp>
24 #include <boost/random/detail/generator_bits.hpp>
31 template<class RealType, std::size_t bits, class URNG>
32 RealType generate_canonical_impl(URNG& g, boost::mpl::true_ /*is_integral*/)
35 typedef typename URNG::result_type base_result;
36 std::size_t digits = std::numeric_limits<RealType>::digits;
37 RealType R = RealType((g.max)()) - RealType((g.min)()) + 1;
41 RealType((std::min)(static_cast<std::size_t>(bits), digits)));
42 RealType S = RealType(detail::subtract<base_result>()(g(), (g.min)()));
44 RealType inc = RealType(detail::subtract<base_result>()(g(), (g.min)()));
51 template<class RealType, std::size_t bits, class URNG>
52 RealType generate_canonical_impl(URNG& g, boost::mpl::false_ /*is_integral*/)
56 BOOST_ASSERT((g.min)() == 0);
57 BOOST_ASSERT((g.max)() == 1);
58 typedef typename URNG::result_type base_result;
59 std::size_t digits = std::numeric_limits<RealType>::digits;
60 std::size_t engine_bits = detail::generator_bits<URNG>::value();
61 std::size_t b = (std::min)(bits, digits);
62 RealType R = pow(RealType(2), RealType(engine_bits));
64 RealType limit = pow(RealType(2), RealType(b));
65 RealType S = RealType(g() - (g.min)());
67 RealType inc(floor((RealType(g()) - RealType((g.min)())) * R));
77 * Returns a value uniformly distributed in the range [0, 1)
78 * with at least @c bits random bits.
80 template<class RealType, std::size_t bits, class URNG>
81 RealType generate_canonical(URNG& g)
83 RealType result = detail::generate_canonical_impl<RealType, bits>(
84 g, boost::is_integral<typename URNG::result_type>());
85 BOOST_ASSERT(result >= 0);
86 BOOST_ASSERT(result <= 1);
88 result -= std::numeric_limits<RealType>::epsilon() / 2;
89 BOOST_ASSERT(result != 1);
97 #endif // BOOST_RANDOM_GENERATE_CANONICAL_HPP