Article 713KD Mentally compute logs base 2

Mentally compute logs base 2

by
John
from John D. Cook on (#713KD)

The previous post required computing

log2eq1.svg

After writing the post, I thought about how you would mentally approximate log2 5. The most crude approximation would round 5 down to 4 and use log2 4 = 2 to approximate log2 5.That would be good enough for an order of magnitude guess, but we can do much better without too much more work.

Simple approximation

I've written before about the approximation

log2eq3.svg

forx between 1/2 and 2. We can write 5 as 4 (5/4) and so

log2eq5.svg

How accurate is this? The exact value of log2 5 is 2.3219.... Approximating this number by 7/3 is much better than approximating it by just 2, reducing the relative error from 16% down to 0.5%.

Origin story

Where did the approximation

log2eq3.svg

come from?

I don't remember where I found it. I wouldn't be surprised if it was from something Ron Doerfler wrote. But how might someone have derived it?

You'd like an approximation that works on the interval from 1/2 to 2 because you can always multiply or divide by a power of 2 to reduce the problem to this interval. Rational approximations are the usual way to approximate functions over an interval [1], and for mental calculation you'd want to use the lowest order possible, i.e. degree 1 in the numerator and denominator.

Here's how we could ask Mathematica to find a rational approximation for us [2].

Simplify[ N[ ResourceFunction["EconomizedRationalApproximation"][ Log[2, x], { x, {1/Sqrt[2], Sqrt[2]}, 1, 1}]]]

This returns

(2.97035 x - 2.97155) / (1.04593 + x)

which we round off to

(3 x - 3) / (1 + x).

The N function turns a symbolic result into one with floating point numbers. Without this call we get a complicated expression involving square roots and logs of rational numbers.

The Simplify function returns an algebraically equivalent but simpler expression for its argument. In our case the function finishes the calculation by removing some parentheses.

Related posts

[1] Power series approximations are easier to compute, but power series approximations don't give the best accuracy over an interval. Power series are excellent at the point where they're centered, but degrade as you move away from the center. Rational approximations spread the error more uniformly.

[2] I first tried using Mathematica's MiniMaxApproximation function, but it ran into numerical problems, so I switched to EconomizedRationalApproximation.

The post Mentally compute logs base 2 first appeared on John D. Cook.
External Content
Source RSS or Atom Feed
Feed Location http://feeds.feedburner.com/TheEndeavour?format=xml
Feed Title John D. Cook
Feed Link https://www.johndcook.com/blog
Reply 0 comments