Created
January 13, 2024 00:13
-
-
Save astoeckel/8411c1ea98ea8768d9d86f991c314b00 to your computer and use it in GitHub Desktop.
Integer log2 with 14-bit fractional part in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def polyval_fixed(coeffs, x, scale): | |
res = 0 | |
for c in coeffs: | |
res = (((x * res) >> scale) + c) | |
return res | |
def log2_approx(x): | |
if x < 1: | |
return 0 | |
# Return the integer logarithm | |
log2_int = 0 | |
x_tmp = x | |
while x_tmp > 1: | |
log2_int += 1 | |
x_tmp >>= 1 | |
# Normalize the fractional part to 31 bits | |
x -= (1 << log2_int) | |
if x <= 0: | |
return log2_int << 14 | |
x = x << (31 - log2_int) | |
# Divide by 2^17, resulting in 14 bit dynamic range | |
x >>= 17 | |
# Evaluate an order-three polynomial evaluating the logarithm on the | |
# fractional part | |
return polyval_fixed([2529, -9324, 23174, 0], x, 14) + (log2_int << 14) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment