Sunday, 4 March 2012

The Natural Logarithmic Functions in C & C++


I am making may way through all the different functions in the various standard header files that form part of C and C++. I’m still working on the contents of the <math.h> or <cmath> header files. Today is about the natural logarithmic functions.

Even though I can’t see myself using these functions, I think it’s important to understand what they do. It’s just part of understanding the limits of the language.

Here’s a brief primer on e and the exp and log functions in C.



A graph of e to the xth power as a function of x.



Here is a snippet from the C standard (C99 N1244).




The exp(n) function returns a float equal to e to the nth power. The log function reverses the process and returns n for a given value of e to the nth power.


Test Code.

I wrote some sample code to test the functions. No unexpected results.

C often uses ++n to increment a counter. It’s shorter version of n = n + 1. But I wanted to increment by 0.5. I could use n = n + 0.5, but C programmers prefer to use: n += 0.5.

Also note in the for loop I assigned -5.0 to n, not -5. One is a float, the other an integer and n was declared as a float.

I tested the functions in Visual C++ 2010 as an console application.


// The standard library includes the system function.
#include <cstdlib>

// C++ standard I/O library.
#include <cstdio>

// C++ math library.
#include <cmath>

int main()
{
     float n;

     // Header.
     printf("Exponential & Logarithmic Functions\n\n");
     printf("n\t  exp(n) \t log(exp(n)) \n\n");

     // Sample calcs.
     for (n = -5.0; n < 6; n += 0.5)
           printf("%5.2f\t%10.6f\t%10.6f\n", n, exp(n), log(exp(n)));

     // Keep console window open.
     system("pause");

     // Return some value.
     return 0;
} // end main


Output.



No comments:

Post a Comment