From 5faeb67a1182708acec28e861461546a7f006320 Mon Sep 17 00:00:00 2001 From: Andrew Belt Date: Fri, 23 Apr 2021 19:38:06 -0400 Subject: [PATCH] Fix `float approxExp2Floor()` to work with negative arguments and arguments above 30. --- include/common.hpp | 13 +++++++++++++ include/dsp/approx.hpp | 5 +++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/include/common.hpp b/include/common.hpp index 663ed10e..0b24b47e 100644 --- a/include/common.hpp +++ b/include/common.hpp @@ -164,6 +164,17 @@ namespace std { namespace rack { +/** Casts a primitive, preserving its bits instead of converting. */ +template +To bitCast(From from) { + static_assert(sizeof(From) == sizeof(To), "Types must be the same size"); + To to; + // This is optimized out + std::memcpy(&to, &from, sizeof(From)); + return to; +} + + /** C#-style property constructor Example: @@ -181,6 +192,7 @@ T* construct(F f, V v, Args... args) { return o; } + /** Defers code until the scope is destructed From http://www.gingerbill.org/article/defer-in-cpp.html Example: @@ -244,6 +256,7 @@ typename C::mapped_type get(const C& m, const typename C::key_type& key, const t return it->second; } + // config extern const std::string APP_NAME; diff --git a/include/dsp/approx.hpp b/include/dsp/approx.hpp index 30d31231..e9c1da8d 100644 --- a/include/dsp/approx.hpp +++ b/include/dsp/approx.hpp @@ -39,10 +39,11 @@ inline simd::float_4 approxExp2Floor(simd::float_4 x, simd::float_4* xf) { template <> inline float approxExp2Floor(float x, float* xf) { - int xi = x; + int32_t xi = x; if (xf) *xf = x - xi; - return 1 << xi; + int32_t y = (xi + 127) << 23; + return bitCast(y); }