Friday, 16 March 2012

The cosh Function in C & C++


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

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



From C11 standard.


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



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

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

     printf("    x   =>  cosh(x) =  0.5 * (exp(x) + 1.0/exp(x)) \n\n");
     for (i = -5; i <= 5; ++i)
     {
           x = i * 1.0;              
           y = cosh(x);
           y2 = 0.5 * (exp(x) + 1.0/exp(x));
           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