Using Logarithms in Delphi - Part II
This Issue we continue
our look at Logarithms and how they can be used in Delphi.
Magnitudes
Ever had the need
to know how many digits (ignoring leading zeroes) a given
Integer has? Yes you could convert it to a string and get
the length, but Logarithms can be used for this as well:
function ESBDigits (const
X: Cardinal): Byte;
// Returns
the number of digits in a given positive integer
begin
if X = 0 then
Result := 0
else
Result := Trunc (Log10 (X)) + 1;
end;
In Delphi 4, X could
be an Int64 plus this could easily be adapted to handle Negative
Integers as well by taking the Absolute Value.
When extending this
to Floating Point Numbers, what we are finding is the Magnitude
of the Number - i.e. How Big a number is irrespective of it's
sign. This is a concept used often in Mathematics, especially in
Physics and Applied Maths.
function
ESBMagnitude (const X: Extended): Integer;
// Returns the Magnitude of a Floating Point
begin
if X < 1 then
Result := 0
else
Result := Trunc (Log10 (Abs (X))) + 1;
end;
Note that we have
now "handled" Negative values. The above could be adapted
to handle decimal values between 0 and 1 as they would be returned
with negative magnitude.
Logarithms to
Base 2
Delphi also supplies
us with a Log2 function which calculates the Logarithm
to Base 2. Now in the previous example, we saw that Log10
told us how many digits or rather the magnitude of a number, well
Log2 of an Integer can tell us how many Bits (Binary Digits)
are needed to store a given integer.
function ESBBitsNeeded
(const X: Cardinal): Byte;
// Returns
the number of digits in a given positive integer
begin
if X = 0 then
Result := 0
else
Result := Trunc (Log2 (X)) + 1;
end;
Once again Delphi
4 uses could update this for Int64. And for Negatives you need one
extra bit.
Logarithms to
Base 16
Suppose we wanted
to know how many Hexadecimal digits were needed to store a given
integer. Well Delphi doesn't supply a Logarithm to Base 16
so how would we get one?
Using the Logarithm
Rules from last week, it is quite easy to write a Log16
function:
function Log16 (const
X: Extended): Extended;
// Computes Logarithm to Base 16
begin
Result := Ln (X) / Ln (16)
end;
In fact Logarithms
of any base can be easily calculated.
Conclusion
Logarithms
can be used for many purposes besides the few covered here.
Next Issue we will
start looking at developing a series of Statistical Routines that
work on Open Arrays of Floating Point values.
|