Example Code
The following Python program computes the binary logarithm using the recursive method outlined above, showing the steps along the way: (This code fails when finding the binary logarithm of any number 2^n where n is any integer.)
def lg(x): ip = 0 rem = x # Integer part while rem<1: ip -= 1 rem *= 2 while rem>=2: ip += 1 rem /= 2 print("lg(%g) = %d + lg(%g)" % (x, ip, rem)) # Brackets required for Python 3 # Fractional part res = ip + frac_lg(rem) return res def frac_lg(x, fp=1.0, tol=1e-10): assert 1<=x<2 # terminate the recursion if we're close enough if fpSince Python does not optimize tail recursion, this can be implemented more efficiently with iteration. Here is an iterative version of the same algorithm in Perl:
sub lg { my $x = shift; my $tol = shift || 1e-13; my $res = 0.0; while ($x < 1) { $res -= 1; $x *= 2; } while ($x >= 2) { $res += 1; $x /= 2; } my $fp = 1.0; while ($fp >= $tol) { $fp /= 2; $x *= $x; if ($x >= 2) { $x /= 2; $res += $fp; } } $res } printf "x = %g\nlg(x) = %g\n", 4.5, lg(4.5);Read more about this topic: Binary Logarithm
Famous quotes containing the word code:
“...I had grown up in a world that was dominated by immature age. Not by vigorous immaturity, but by immaturity that was old and tired and prudent, that loved ritual and rubric, and was utterly wanting in curiosity about the new and the strange. Its era has passed away, and the world it made has crumbled around us. Its finest creation, a code of manners, has been ridiculed and discarded.”
—Ellen Glasgow (18731945)
“Wise Draco comes, deep in the midnight roll
Of black artillery; he comes, though late;
In code corroborating Calvins creed
And cynic tyrannies of honest kings;
He comes, nor parlies; and the Town, redeemed,
Gives thanks devout; nor, being thankful, heeds
The grimy slur on the Republics faith implied,
Which holds that Man is naturally good,
Andmoreis Natures Roman, never to be
scourged.”
—Herman Melville (18191891)