Saturday, 17 March 2012

The tanh Function in C & C++


More functions from the  <math.h> or <cmath> header files. Today it’s about the tanh function.

The tanh function returns the hyperbolic tangent for any real number and is defined as shown below.


 


From C11 standard.


The newest standard includes the atanh function, but it is not implemented in Visual C++ 2010; however, you can use the log function to determine the arc hyperbolic tangent.

 

Test Code.

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()
{
     // Header.
     printf("The tanh Function in C & C++\n\n");
     printf("Given x, any real number, the function returns y \n");
     printf("equal to the hyperbolic tangent of x.\n\n");

     // Counter for loop.
     int i;
     // Argument.
     double x;
     // Result.
     double y, y2;

     printf("    x   =>  tanh(x) = (exp(2*x) - 1.0) / (exp(2*x) + 1.0) \n\n");
     for (i = -5; i <= 5; ++i)
    {
           x = i * 1.0;              
           y = tanh(x);
           y2 = (exp(2*x) - 1.0) / (exp(2*x) + 1.0);
           printf ("%6.1f  => %8.4f = %8.4f\n", x, y, y2);
     }
     // Keep console window open.
     system("pause");

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


Output.



No comments:

Post a Comment