

Recursive calculation of logarithms 


download program.
download Delphi7 project.
In this article I describe a recursive method to calculate the logarithm of a number.
The programming language is Delphi.
Chained fractions
This is the general format of a chained fraction:
where a_{i} is an integer > 0.
The impact of a_{i} becomes smaller as i increases.
Within a chained fraction the integer part of a number is extracted, leaving a fraction.
The reciproce of this fraction again has an integer part which may be extracted.....
Such a method can be implemented by a recursive procedure.
Logarithms
^{g}log(a) = x means: g^{x} = a
Calculation the logarithm of a number amounts to writing that number as
a base number powered to an exponent and removing the base.
Some rules for logarithms are:
^{g}log(g) = 1
^{g}log(a^{n}) = n.^{g}log(a)
^{g}log(a.b) = ^{g}log(a) + ^{g}log(b)
^{a}log(b) = ^{g}log(b)/^{g}log(a)...and consequently
^{a}log(b) = 1 / ^{b}log(a)
Now we calculate ^{b}log(a) and suppose a > b.
(b : base).
a is rewritten as : a = b^{c}.x
where c is a positive integer such that b^{c} < a < b^{c+1}.
The remaining factor x = a/b^{c} < b.
^{b}log(a) =  ^{b}log(b^{c}.x)

=  ^{b}log(b^{c}) + ^{b}log(x) 
=  c + ^{b}log(x) 
=  c + 1 / ^{x}log(b) 
and the process repeats itself because b > x.
Recursion
Recursive procedures call themselve.
Because parameters and locally declared variables exist on the stack,
they are unique for each call.
Recursive procedures are very powerfull but also hard to understand.
What helps is to regard them as many different procedures which accomplish the same.
The program
Here is the recursive function:
function recLog(b,a : double) : double;
//recursive logarithm calculation
//b : base; a : number
var c : byte;
b2,bt : double;
GO : boolean;
begin
c := 0;
b2 := 1;
repeat
bt := b2 * b;
GO := a >= bt;
if GO then begin
inc(c);
b2 := b2 * b;
end;
until GO = false;
a := a/b2;
if a > 1.000001 then result := c + 1/reclog(a,b)
else result := c;
end;
Each step brings a closer to 1 and this makes the test to call the function again.
Variable c is the biggest power of b that fits a.
The successive values of c make the chained fraction.
Please refer to the source code for details of this small Delphi7 project.

