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