cosh() Function

The cosh() function in C computes the hyperbolic cosine of a given value, providing a measure analogous to the cosine function for hyperbolic angles. It is commonly used in mathematical computations involving hyperbolic functions and complex analyses.


Syntax of cosh()

</>
Copy
double cosh(double x);
float coshf(float x);
long double coshl(long double x);

Parameters

ParameterDescription
xValue representing a hyperbolic angle.

Note: If the resulting value exceeds the range representable by the return type, the function returns HUGE_VAL (or its float/long double equivalents) and an overflow error is indicated.


Examples for cosh()

Example 1: Calculating the Hyperbolic Cosine for a Typical Angle

This example demonstrates the use of cosh() to calculate the hyperbolic cosine of a typical positive value.

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    double x = 1.0;
    double result = cosh(x);
    printf("cosh(%.1f) = %f\n", x, result);
    return 0;
}

Explanation:

  1. A variable is initialized with a typical hyperbolic angle value.
  2. The cosh() function computes the hyperbolic cosine of the given value.
  3. The result is then printed to the console.

Program Output:

cosh(1.0) = 1.543081

Example 2: Using coshf() to Compute the Hyperbolic Cosine for a Float Value

This example illustrates how to compute the hyperbolic cosine for a floating-point value using the coshf() variant.

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    float x = 0.5f;
    float result = coshf(x);
    printf("coshf(%.1f) = %f\n", x, result);
    return 0;
}

Explanation:

  1. A float variable is defined with a small hyperbolic angle value.
  2. The coshf() function calculates the hyperbolic cosine for the float value.
  3. The computed result is displayed using printf().

Program Output:

coshf(0.5) = 1.127626

Example 3: Handling Overflow with a Large Hyperbolic Angle

This example demonstrates how to check for an overflow when computing the hyperbolic cosine of a very large value.

Program

</>
Copy
#include <stdio.h>
#include <math.h>
#include <errno.h>

int main() {
    double x = 1000.0;
    errno = 0;
    double result = cosh(x);
    if (errno == ERANGE) {
        printf("Overflow occurred for cosh(%.1f)\n", x);
    } else {
        printf("cosh(%.1f) = %f\n", x, result);
    }
    return 0;
}

Explanation:

  1. A very large hyperbolic angle value is assigned to trigger potential overflow.
  2. The error number (errno) is reset before computation.
  3. The cosh() function is called to compute the result.
  4. The program checks if an overflow occurred by examining errno and prints an appropriate message.

Program Output:

Overflow occurred for cosh(1000.0)