From 13fabcc1f1e6de9acf75842ab720ecd4b4dece24 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Wed, 10 May 2023 19:03:33 +0300 Subject: [PATCH] BAN: add pow, log2, log10, log in math These are implemented using x86 floating point assembly --- BAN/include/BAN/Math.h | 43 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/BAN/include/BAN/Math.h b/BAN/include/BAN/Math.h index 8302decf18..a5eeb44b7d 100644 --- a/BAN/include/BAN/Math.h +++ b/BAN/include/BAN/Math.h @@ -59,6 +59,49 @@ namespace BAN::Math return (value & (value - 1)) == 0; } + template + inline constexpr T log2(T value) + { + T result; + asm volatile("fyl2x" : "=t"(result) : "0"(value), "u"((T)1.0) : "st(1)"); + return result; + } + + template + inline constexpr T log10(T value) + { + constexpr T INV_LOG_2_10 = 0.3010299956639811952137388947244930267681898814621085413104274611; + T result; + asm volatile("fyl2x" : "=t"(result) : "0"(value), "u"(INV_LOG_2_10) : "st(1)"); + return result; + } + + template + inline constexpr T log(T value, T base) + { + return log2(value) / log2(base); + } + + template + inline constexpr T pow(T base, T exp) + { + T result; + asm volatile( + "fyl2x;" + "fld1;" + "fld %%st(1);" + "fprem;" + "f2xm1;" + "faddp;" + "fscale;" + "fxch %%st(1);" + "fstp %%st;" + : "=t"(result) + : "0"(base), "u"(exp) + ); + return result; + } + template inline constexpr T little_endian_to_host(const uint8_t* bytes) {