Logarithm Function (Pascal)

From LiteratePrograms

Jump to: navigation, search
Other implementations: Pascal | Python | Python, functional

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

The algorithm of finding the logarithm in base b of a positive real number x is a tricky thing, and you can read about it in the article describing this function in the Python language. Here we'll just write a program to find it for those who need it but aren't interested in learning too much mathematics.

The logarithm has a unique property, namely

This means that we can write the logarithm of any given base using any other base. Possibly every language supports finding logarithms, either natural (ln, with the base of e) or common (the base of 10). Pascal can find natural logarithms with its ln function. All we need do is write a program converting any base to e and then calculating the logarithm according to the aforementioned formula.

So let's begin.

<<Logarithm.pas>>=
program Logarithm; 
var
  a, b : integer; {''a'' is the number of decimal points of the mantissa we want the computer tocalculate}
  x, i : real;   {''b'' is the base, ''x'' is our value. We'll need ''i'' later}
begin
  writeln ('Enter the base "b" of your logarithm and press Enter');
  readln (b); 
  writeln ('Enter the value of your logarithm and press Enter');
  readln (x);  {Now the computer knows the base and the value of the expression}
  writeln ('How many decimal places (up to 16) should it have?'); 
                              {This is how precise you want the computer to be.}
                              {Unfortunately it can calculate only up to the 16-th digit}
  readln (a); 
  i := ln(x)/ln(b);  {Now we use our formula, that's why we need a new variable}
  writeln ('The base-',b, ' logarithm of ', x:3:3, ' = ', i:3:a); {Here is the output}
                                        {Digits mean how long the representation should be, ''a'' also treated as digit} 
  readln    {This is for you to have enough time to read the result}       
end. {The end:)}
Download code
Views