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 20 #ifndef NLP_SAFT_COMPONENTS_COMMON_MOBILE_MATH_FASTEXP_H_ 21 #define NLP_SAFT_COMPONENTS_COMMON_MOBILE_MATH_FASTEXP_H_ 22 23 #include <cassert> 24 #include <cmath> 25 #include <limits> 26 27 #include "lang_id/common/lite_base/casts.h" 28 #include "lang_id/common/lite_base/integral-types.h" 29 #include "lang_id/common/lite_base/logging.h" 30 31 namespace libtextclassifier3 { 32 namespace mobile { 33 34 class FastMathClass { 35 private: 36 static constexpr int kBits = 7; 37 static constexpr int kMask1 = (1 << kBits) - 1; 38 static constexpr int kMask2 = 0xFF << kBits; 39 static constexpr float kLogBase2OfE = 1.44269504088896340736f; 40 41 struct Table { 42 int32 exp1[1 << kBits]; 43 }; 44 45 public: VeryFastExp2(float f)46 float VeryFastExp2(float f) const { 47 SAFTM_DCHECK_LE(fabs(f), 126); 48 const float g = f + (127 + (1 << (23 - kBits))); 49 const int32 x = bit_cast<int32>(g); 50 int32 ret = ((x & kMask2) << (23 - kBits)) 51 | cache_.exp1[x & kMask1]; 52 return bit_cast<float>(ret); 53 } 54 VeryFastExp(float f)55 float VeryFastExp(float f) const { 56 return VeryFastExp2(f * kLogBase2OfE); 57 } 58 59 private: 60 static const Table cache_; 61 }; 62 63 extern FastMathClass FastMathInstance; 64 VeryFastExp(float f)65inline float VeryFastExp(float f) { return FastMathInstance.VeryFastExp(f); } 66 67 } // namespace mobile 68 } // namespace nlp_saft 69 70 #endif // NLP_SAFT_COMPONENTS_COMMON_MOBILE_MATH_FASTEXP_H_ 71