fastmath.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #ifndef Y_ABSL_RANDOM_INTERNAL_FASTMATH_H_
  15. #define Y_ABSL_RANDOM_INTERNAL_FASTMATH_H_
  16. // This file contains fast math functions (bitwise ops as well as some others)
  17. // which are implementation details of various y_absl random number distributions.
  18. #include <cassert>
  19. #include <cmath>
  20. #include <cstdint>
  21. #include "y_absl/numeric/bits.h"
  22. namespace y_absl {
  23. Y_ABSL_NAMESPACE_BEGIN
  24. namespace random_internal {
  25. // Compute log2(n) using integer operations.
  26. // While std::log2 is more accurate than std::log(n) / std::log(2), for
  27. // very large numbers--those close to std::numeric_limits<uint64_t>::max() - 2,
  28. // for instance--std::log2 rounds up rather than down, which introduces
  29. // definite skew in the results.
  30. inline int IntLog2Floor(uint64_t n) {
  31. return (n <= 1) ? 0 : (63 - countl_zero(n));
  32. }
  33. inline int IntLog2Ceil(uint64_t n) {
  34. return (n <= 1) ? 0 : (64 - countl_zero(n - 1));
  35. }
  36. inline double StirlingLogFactorial(double n) {
  37. assert(n >= 1);
  38. // Using Stirling's approximation.
  39. constexpr double kLog2PI = 1.83787706640934548356;
  40. const double logn = std::log(n);
  41. const double ninv = 1.0 / static_cast<double>(n);
  42. return n * logn - n + 0.5 * (kLog2PI + logn) + (1.0 / 12.0) * ninv -
  43. (1.0 / 360.0) * ninv * ninv * ninv;
  44. }
  45. } // namespace random_internal
  46. Y_ABSL_NAMESPACE_END
  47. } // namespace y_absl
  48. #endif // Y_ABSL_RANDOM_INTERNAL_FASTMATH_H_