Home | History | Annotate | Download | only in math
      1 /*
      2  * Copyright (C) 2017 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 // Fast approximation for exp.
     18 
     19 #ifndef LIBTEXTCLASSIFIER_UTIL_MATH_FASTEXP_H_
     20 #define LIBTEXTCLASSIFIER_UTIL_MATH_FASTEXP_H_
     21 
     22 #include <cassert>
     23 #include <cmath>
     24 #include <limits>
     25 
     26 #include "util/base/casts.h"
     27 #include "util/base/integral_types.h"
     28 #include "util/base/logging.h"
     29 
     30 namespace libtextclassifier2 {
     31 
     32 class FastMathClass {
     33  private:
     34   static const int kBits = 7;
     35   static const int kMask1 = (1 << kBits) - 1;
     36   static const int kMask2 = 0xFF << kBits;
     37   static constexpr float kLogBase2OfE = 1.44269504088896340736f;
     38 
     39   struct Table {
     40     int32 exp1[1 << kBits];
     41   };
     42 
     43  public:
     44   float VeryFastExp2(float f) const {
     45     TC_DCHECK_LE(fabs(f), 126);
     46     const float g = f + (127 + (1 << (23 - kBits)));
     47     const int32 x = bit_cast<int32>(g);
     48     int32 ret = ((x & kMask2) << (23 - kBits))
     49       | cache_.exp1[x & kMask1];
     50     return bit_cast<float>(ret);
     51   }
     52 
     53   float VeryFastExp(float f) const {
     54     return VeryFastExp2(f * kLogBase2OfE);
     55   }
     56 
     57  private:
     58   static const Table cache_;
     59 };
     60 
     61 extern FastMathClass FastMathInstance;
     62 
     63 inline float VeryFastExp2(float f) { return FastMathInstance.VeryFastExp2(f); }
     64 inline float VeryFastExp(float f) { return FastMathInstance.VeryFastExp(f); }
     65 
     66 }  // namespace libtextclassifier2
     67 
     68 #endif  // LIBTEXTCLASSIFIER_UTIL_MATH_FASTEXP_H_
     69