ADUG
Home
About Us
Services
Meetings
Fees
Mailing List
Rules
Reference Papers
Downloads
Apply to Join
Links
Delphi Jobs
Special Offers
Maths Corner

 

by Glenn Crouch

 

Using Logarithms in Delphi - Part I

No, we will not be building a nice cabin for your Winter retreat. Instead, we will be examining some of the uses of Logarithms.

Logarithms were discovered by John Napier in the 17th Century as a way of doing fast multiplication by doing addition. If you wanted to multiply 123.45 by 41.512, you would first find the logarithm of each number, then add them together, and then find the antilogarithm of the result - this would be the answer. So instead of difficult multiplication, we had three table lookups and one addition. Logarithms would also be the principle behind the slide rule (what engineers used before pocket calculators).

So Logs have a long history. But of what use are they to the Delphi Programmer today?

First we need to see some basic Log Rules:

Delphi supplies two logarithmic functions: logarithm to base 10 - log10 () - and the logarithm to base e (which is the natural constant 2.71828183...) - ln () - the latter is also called the natural logarithm. The above rules work with both of these Delphi functions.

Power function

With Delphi Professional and C/S we now get a Math unit, but if you have standard, then you are without a power function, like back in the good ol' Turbo Pascal days.

Logarithms give us away around this as the Power Function is in fact an Antilogarithm. The Maths behind writing a power function, using the above rules, is as follows:

translating this into Delphi we have:

function ESBPower (const X, Y: Extended): Extended;
// Returns X to the Power of Y
begin
   Result := exp (y * ln(x));
end;

We need to realise that logarithms only exist for Positive value, i.e. values strictly greater than zero. Well 0 raised to any power  is defined as 0, and negative numbers raised to powers are only defined for integer powers (unless of course you are interested in complex numbers).

So we will modify our function accordingly:

function ESBPower (const X, Y: Extended): Extended;
//
Returns X to the Power of Y
begin
  if
X = 0.0 then
// Could also use a tolerance here
   
Result := 0.0
  else if X > 0.0 then
   
Result := exp(y * ln(x))
  else
raise Exception.Create ('ESBPower does not handle Negative Bases')
end;

You could of course write a function that raises an Extended to an Integer power and then use this to replace the exception above. I will leave this as an exercise for you.

Will we continue our look into the uses for the Logarithmic functions next issue, as we see how we can calculate magnitudes, uses for logarithms to base 2, and more.

 

Maths Corner Home

 Copyright © 2001 Australian Delphi User Group and respective copyright owners.
All Rights Reserved | Disclaimer