00001 /** 00002 * \file RandomPower2.hpp 00003 * \brief Header for RandomPower2. 00004 * 00005 * Return and multiply by powers of two. 00006 * 00007 * Written by <a href="http://charles.karney.info/">Charles Karney</a> 00008 * <charles@karney.com> and licensed under the LGPL. For more 00009 * information, see http://charles.karney.info/random/ 00010 **********************************************************************/ 00011 00012 #if !defined(RANDOMPOWER2_HPP) 00013 #define RANDOMPOWER2_HPP "$Id: RandomPower2.hpp 6419 2008-01-16 18:23:01Z ckarney $" 00014 00015 #include <cmath> // For std::pow 00016 00017 namespace RandomLib { 00018 00019 /** 00020 * \brief Return or multiply by powers of 2 00021 * 00022 * With some compilers it's fastest to do a table lookup of powers of 00023 * 2. If RANDOM_POWERTABLE is 1, a lookup table is used. If 00024 * RANDOM_POWERTABLE is 0, then std::pow is used. 00025 **********************************************************************/ 00026 class RandomPower2 { 00027 public: 00028 /** 00029 * Return powers of 2 (either using a lookup table or std::pow) 00030 **********************************************************************/ 00031 template<typename RealType> static inline RealType pow2(int n) throw() { 00032 #if RANDOM_POWERTABLE 00033 return RealType(power2[n - minpow]); 00034 #else 00035 return std::pow(RealType(2), n); 00036 #endif 00037 } 00038 /** 00039 * Multiply a real by a power of 2 00040 **********************************************************************/ 00041 template<typename RealType> 00042 static inline RealType shiftf(RealType x, int n) throw() 00043 // std::ldexp(x, n); is equivalent, but slower 00044 { return x * pow2<RealType>(n); } 00045 00046 // Constants 00047 enum { 00048 /** 00049 * Minimum power in RandomPower2::power2 00050 **********************************************************************/ 00051 #if RANDOM_LONGDOUBLEPREC > 64 00052 minpow = -120, 00053 #else 00054 minpow = -64, 00055 #endif 00056 maxpow = 64 /**< Maximum power in RandomPower2::power2. */ 00057 }; 00058 private: 00059 #if RANDOM_POWERTABLE 00060 /** 00061 * Table of powers of two 00062 **********************************************************************/ 00063 static const float power2[maxpow - minpow + 1]; // Powers of two 00064 #endif 00065 }; 00066 00067 } // namespace RandomLib 00068 00069 #endif // RANDOMPOWER2_HPP