RandomLib  1.10
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Pages
RandomPower2.hpp
Go to the documentation of this file.
1 /**
2  * \file RandomPower2.hpp
3  * \brief Header for RandomPower2.
4  *
5  * Return and multiply by powers of two.
6  *
7  * Copyright (c) Charles Karney (2006-2011) <charles@karney.com> and licensed
8  * under the MIT/X11 License. For more information, see
9  * http://randomlib.sourceforge.net/
10  **********************************************************************/
11 
12 #if !defined(RANDOMLIB_RANDOMPOWER2_HPP)
13 #define RANDOMLIB_RANDOMPOWER2_HPP 1
14 
15 #include <cmath> // For std::pow
16 
17 namespace RandomLib {
18 
19  /**
20  * \brief Return or multiply by powers of 2
21  *
22  * With some compilers it's fastest to do a table lookup of powers of
23  * 2. If RANDOMLIB_POWERTABLE is 1, a lookup table is used. If
24  * RANDOMLIB_POWERTABLE is 0, then std::pow is used.
25  **********************************************************************/
27  public:
28  /**
29  * Return powers of 2 (either using a lookup table or std::pow)
30  *
31  * @param[in] n the integer power.
32  * @return 2<sup><i>n</i></sup>.
33  **********************************************************************/
34  template<typename RealType> static inline RealType pow2(int n) throw() {
35 #if RANDOMLIB_POWERTABLE
36  return RealType(power2[n - minpow]);
37 #else
38  return std::pow(RealType(2), n);
39 #endif
40  }
41  /**
42  * Multiply a real by a power of 2
43  *
44  * @tparam RealType the type of \e x.
45  * @param[in] x the real number.
46  * @param[in] n the power (positive or negative).
47  * @return \e x 2<sup><i>n</i></sup>.
48  **********************************************************************/
49  template<typename RealType>
50  static inline RealType shiftf(RealType x, int n) throw()
51  // std::ldexp(x, n); is equivalent, but slower
52  { return x * pow2<RealType>(n); }
53 
54  // Constants
55  enum {
56  /**
57  * Minimum power in RandomPower2::power2
58  **********************************************************************/
59 #if RANDOMLIB_LONGDOUBLEPREC > 64
60  minpow = -120,
61 #else
62  minpow = -64,
63 #endif
64  maxpow = 64 /**< Maximum power in RandomPower2::power2. */
65  };
66  private:
67 #if RANDOMLIB_POWERTABLE
68  /**
69  * Table of powers of two
70  **********************************************************************/
71  static const float power2[maxpow - minpow + 1]; // Powers of two
72 #endif
73  };
74 
75 } // namespace RandomLib
76 
77 #endif // RANDOMLIB_RANDOMPOWER2_HPP
static RealType pow2(int n)
static RealType shiftf(RealType x, int n)
#define RANDOMLIB_EXPORT
Definition: Random.hpp:83
Return or multiply by powers of 2.