• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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_UTILS_MATH_FASTEXP_H_
20 #define LIBTEXTCLASSIFIER_UTILS_MATH_FASTEXP_H_
21 
22 #include <cassert>
23 #include <cmath>
24 #include <limits>
25 
26 #include "utils/base/casts.h"
27 #include "utils/base/integral_types.h"
28 #include "utils/base/logging.h"
29 
30 namespace libtextclassifier3 {
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:
VeryFastExp2(float f)44   float VeryFastExp2(float f) const {
45     TC3_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 
VeryFastExp(float f)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 
VeryFastExp(float f)63 inline float VeryFastExp(float f) { return FastMathInstance.VeryFastExp(f); }
64 
65 }  // namespace libtextclassifier3
66 
67 #endif  // LIBTEXTCLASSIFIER_UTILS_MATH_FASTEXP_H_
68