Logarithm Function (Python)
From LiteratePrograms
Contents |
Logarithm function
The logarithm function performs a mathematical operation that is the inverse of an exponentiation function (raising a constant, the base, to a power). The logarithm of a number x in base b is any number n such that x = bn. It is usually written as
Finding the logarithm in base b of a positive real number x can be done in two parts:
- Finding the integer part of the logarithm
- Finding the fractional part of the logarithm
1. Finding the integer part
Finding the integer part can be done by simply dividing the number x by the base b until it is no longer larger than the base b. The integer part is the number of iterations we do the division.
For example: Find log base 3 of 161.64
iteration no 1 | 161.64 / 3 = 53.88 | |
iteration no 2 | 53.88 / 3 = 17.96 | |
iteration no 3 | 17.96 / 3 = 5.9866 | |
iteration no 4 | 5.9866 / 3 = 1.9955 |
As it takes 4 iterations, the integer part of the logarithm is 4.
2. Finding the fractional part
To find the fractional part, we use the fact that multiplying a logarithm number by two is equivalent to squaring.
Example: find fractional part of 161.64 in log base 3
- thus
Next we square both sides
Because 3.98 is greater than 3, we can write:
- thus
Next we concentrate on f1
- becomes
Next we repeat the trick of squaring both sides
Because 1.76 is less than 3, we can write:
thus:
Next we concentrate on f2
- becomes
With the general procedure established above, we can calculate , , , and so on.
Recapping, we have:
and
thus creating
In general, we have
or
- Where is either 1 or 0
Source Code
<<logN.py>>= #!/usr/bin/python from __future__ import division import math def logN(X,base=math.e,epsilon = 1e-12): # logN is logarithm function with the default base of e integer_value=0 while X < 1: integer_value = integer_value - 1 X = X * base while X >= base: integer_value = integer_value + 1 X = X / base partial = 0.5 # partial = 1/2 list=[] # Prepare an empty list X=X*X # We perform a squaring while partial > epsilon: if X >= base: # If X >= base then a_k is 1 list.insert(0,partial) # Insert partial to the front of the list X = X / base # Since a_k is 1, we divide the number by the base partial = partial * 0.5 # partial = partial / 2 X=X*X # We perform the squaring again decimal_fraction = 0.0 for p in list: # Add up all the elements in the list decimal_fraction = decimal_fraction + p return (integer_value + decimal_fraction) if __name__ == '__main__': value = 4.5 print " X =",value print " ln(X) =",logN(value) print " log4(X) =",logN(value,4)
Sample Run
$ python logN.py X = 4.5 ln(X) = 1.50407739678 log4(X) = 1.08496250072
Download code |