• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_COMMON_FASTEXP_H_
20 #define LIBTEXTCLASSIFIER_COMMON_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 libtextclassifier {
31 namespace nlp_core {
32 
33 class FastMathClass {
34  private:
35   static const int kBits = 7;
36   static const int kMask1 = (1 << kBits) - 1;
37   static const int kMask2 = 0xFF << kBits;
38   static constexpr float kLogBase2OfE = 1.44269504088896340736f;
39 
40   struct Table {
41     int32 exp1[1 << kBits];
42   };
43 
44  public:
VeryFastExp2(float f)45   float VeryFastExp2(float f) const {
46     TC_DCHECK_LE(fabs(f), 126);
47     const float g = f + (127 + (1 << (23 - kBits)));
48     const int32 x = bit_cast<int32>(g);
49     int32 ret = ((x & kMask2) << (23 - kBits))
50       | cache_.exp1[x & kMask1];
51     return bit_cast<float>(ret);
52   }
53 
VeryFastExp(float f)54   float VeryFastExp(float f) const {
55     return VeryFastExp2(f * kLogBase2OfE);
56   }
57 
58  private:
59   static const Table cache_;
60 };
61 
62 extern FastMathClass FastMathInstance;
63 
VeryFastExp2(float f)64 inline float VeryFastExp2(float f) { return FastMathInstance.VeryFastExp2(f); }
VeryFastExp(float f)65 inline float VeryFastExp(float f) { return FastMathInstance.VeryFastExp(f); }
66 
67 }  // namespace nlp_core
68 }  // namespace libtextclassifier
69 
70 #endif  // LIBTEXTCLASSIFIER_COMMON_FASTEXP_H_
71