You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.8KB

  1. #pragma once
  2. #include <dsp/common.hpp>
  3. namespace rack {
  4. namespace dsp {
  5. /*
  6. In this header, function names are divided into two or more parts, separated by "_".
  7. The functionality is the first part, and the approximation methods are the following parts.
  8. Glossary:
  9. https://en.wikipedia.org/wiki/Taylor_series
  10. https://en.wikipedia.org/wiki/Pad%C3%A9_approximant
  11. https://en.wikipedia.org/wiki/Horner%27s_method
  12. https://en.wikipedia.org/wiki/Estrin%27s_scheme
  13. */
  14. /** Returns 2^floor(x), assuming that x >= 0.
  15. If `xf` is non-NULL, it is set to the fractional part of x.
  16. */
  17. template <typename T>
  18. T approxExp2Floor(T x, T* xf);
  19. template <>
  20. inline simd::float_4 approxExp2Floor(simd::float_4 x, simd::float_4* xf) {
  21. simd::int32_4 xi = x;
  22. if (xf)
  23. *xf = x - simd::float_4(xi);
  24. // Set float exponent directly
  25. // https://stackoverflow.com/a/57454528/272642
  26. simd::int32_4 y = (xi + 127) << 23;
  27. return simd::float_4::cast(y);
  28. }
  29. template <>
  30. inline float approxExp2Floor<float>(float x, float* xf) {
  31. int xi = x;
  32. if (xf)
  33. *xf = x - xi;
  34. return 1 << xi;
  35. }
  36. /** Returns 2^x, assuming that x >= 0.
  37. Maximum 0.00024% error.
  38. Roughly 7x faster than `std::pow(2, x)`.
  39. If negative powers are needed, you may use a lower bound and rescale.
  40. approxExp2(x + 20) / 1048576
  41. */
  42. template <typename T>
  43. T approxExp2_taylor5(T x) {
  44. // Use bit-shifting for integer part of x.
  45. T y = approxExp2Floor(x, &x);
  46. // 5th order expansion of 2^x around 0.4752 in Horner form.
  47. // The center is chosen so that the endpoints of [0, 1] have equal error, creating no discontinuity at integers.
  48. y *= T(0.9999976457798443) + x * (T(0.6931766804601935) + x * (T(0.2400729486415728) + x * (T(0.05592817518644387) + x * (T(0.008966320633544) + x * T(0.001853512473884202)))));
  49. return y;
  50. }
  51. } // namespace dsp
  52. } // namespace rack