Skip to content

Instantly share code, notes, and snippets.

@astoeckel
Created January 13, 2024 00:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astoeckel/8411c1ea98ea8768d9d86f991c314b00 to your computer and use it in GitHub Desktop.
Save astoeckel/8411c1ea98ea8768d9d86f991c314b00 to your computer and use it in GitHub Desktop.
Integer log2 with 14-bit fractional part in Python
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