fast_math.cc (2288B)
1 /* 2 * Copyright (c) 2019 The WebRTC project authors. All Rights Reserved. 3 * 4 * Use of this source code is governed by a BSD-style license 5 * that can be found in the LICENSE file in the root of the source 6 * tree. An additional intellectual property rights grant can be found 7 * in the file PATENTS. All contributing project authors may 8 * be found in the AUTHORS file in the root of the source tree. 9 */ 10 11 #include "modules/audio_processing/ns/fast_math.h" 12 13 #include <cmath> 14 #include <cstddef> 15 #include <cstdint> 16 #include <numbers> 17 18 #include "api/array_view.h" 19 #include "rtc_base/checks.h" 20 21 namespace webrtc { 22 23 namespace { 24 25 float FastLog2f(float in) { 26 RTC_DCHECK_GT(in, .0f); 27 // Read and interpret float as uint32_t and then cast to float. 28 // This is done to extract the exponent (bits 30 - 23). 29 // "Right shift" of the exponent is then performed by multiplying 30 // with the constant (1/2^23). Finally, we subtract a constant to 31 // remove the bias (https://en.wikipedia.org/wiki/Exponent_bias). 32 union { 33 float dummy; 34 uint32_t a; 35 } x = {in}; 36 float out = x.a; 37 out *= 1.1920929e-7f; // 1/2^23 38 out -= 126.942695f; // Remove bias. 39 return out; 40 } 41 42 } // namespace 43 44 float SqrtFastApproximation(float f) { 45 // TODO(peah): Add fast approximate implementation. 46 return sqrtf(f); 47 } 48 49 float Pow2Approximation(float p) { 50 // TODO(peah): Add fast approximate implementation. 51 return powf(2.f, p); 52 } 53 54 float PowApproximation(float x, float p) { 55 return Pow2Approximation(p * FastLog2f(x)); 56 } 57 58 float LogApproximation(float x) { 59 constexpr float kLogOf2 = std::numbers::ln2_v<float>; 60 return FastLog2f(x) * kLogOf2; 61 } 62 63 void LogApproximation(ArrayView<const float> x, ArrayView<float> y) { 64 for (size_t k = 0; k < x.size(); ++k) { 65 y[k] = LogApproximation(x[k]); 66 } 67 } 68 69 float ExpApproximation(float x) { 70 constexpr float kLog10Ofe = std::numbers::log10e_v<float>; 71 return PowApproximation(10.f, x * kLog10Ofe); 72 } 73 74 void ExpApproximation(ArrayView<const float> x, ArrayView<float> y) { 75 for (size_t k = 0; k < x.size(); ++k) { 76 y[k] = ExpApproximation(x[k]); 77 } 78 } 79 80 void ExpApproximationSignFlip(ArrayView<const float> x, ArrayView<float> y) { 81 for (size_t k = 0; k < x.size(); ++k) { 82 y[k] = ExpApproximation(-x[k]); 83 } 84 } 85 86 } // namespace webrtc