wolfboyft wrote: ↑
Sun Jan 12, 2020 3:52 pm
What range will b be in? What's the resolution of the table?
Actually, forget that. I forgot we have math.frexp. This returns a mantissa between 0.5 and 1, and an exponent for a base of 2, i.e. it returns two numbers that are the decomposition of the input to the form m*2^x (m being the mantissa and x the exponent) with 0.5 <= m < 1. Actually if the input is negative or zero, so is m, so be careful to give an error in that case.
Multiplying the mantissa by 2 gives you a number in the 1..2 range, as required by the algorithm, so we use this instead:
original number = m*2^x = (m*2)*2^(x-1) (taking one of the twos from the power and "attaching" it to m)
Now, taking logarithms at both sides:
ln(original number) = ln(m*2^x) = ln((m*2)*2^(x-1))
... = ln(m*2) + ln(2^(x-1)) (because the logarithm of the product is the sum of the logarithms)
... = ln(m*2) + (x-1)*ln(2) (because the logarithm of a power is the exponent times the logarithm of the base)
and we can stop there. Have the value of ln(2) precalculated (edit: that's 0.6931471805599453), multiply that by the exponent minus 1, and add that to the result of the algorithm as applied to twice the mantissa. There's only a catch: if m is 0.5, m*2 is 1, and the ln algorithm is not prepared to work for that input, but we know that ln(1) = 0 so you can make that a special case and just return (x-1)*ln(2) if that happens.