00001 //---------------------------------------------------------------------------- 00002 /** @file SgFastLog.h 00003 Fast logarithm. */ 00004 //---------------------------------------------------------------------------- 00005 00006 #ifndef SG_FASTLOG_H 00007 #define SG_FASTLOG_H 00008 00009 //---------------------------------------------------------------------------- 00010 00011 /** Fast logarithm. 00012 Computes a fast single precision logarithm based on a lookup table. 00013 00014 O. Vinyals, G. Friedland, N. Mirghafori: Revisiting a basic function on 00015 current CPUs: A fast logarithm implementation with adjustable accuracy. 00016 http://www.icsi.berkeley.edu/pubs/techreports/TR-07-002.pdf 00017 00018 The implementation assumes that the platform uses IEEE 754 floats. */ 00019 class SgFastLog 00020 { 00021 public: 00022 SgFastLog(int mantissaBits); 00023 00024 ~SgFastLog(); 00025 00026 /** Get natural logarithm. */ 00027 float Log(float val) const; 00028 00029 private: 00030 union IntFloat 00031 { 00032 int m_int; 00033 00034 float m_float; 00035 }; 00036 00037 static const int MAX_MANTISSA_BITS = 23; 00038 00039 const int m_mantissaBitsDiff; 00040 00041 float* m_lookupTable; 00042 00043 /** Not implemented. */ 00044 SgFastLog(const SgFastLog&); 00045 00046 /** Not implemented. */ 00047 SgFastLog& operator=(const SgFastLog&); 00048 }; 00049 00050 inline float SgFastLog::Log(float val) const 00051 { 00052 IntFloat x; 00053 x.m_float = val; 00054 int logTwo = ((x.m_int >> MAX_MANTISSA_BITS) & 255) - 127; 00055 x.m_int &= 0x7FFFFF; 00056 x.m_int >>= m_mantissaBitsDiff; 00057 return ((m_lookupTable[x.m_int] + float(logTwo)) * 0.69314718f); 00058 } 00059 00060 //---------------------------------------------------------------------------- 00061 00062 #endif // SG_FASTLOG_H