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()
double cosh(double x);
float coshf(float x);
long double coshl(long double x);
Parameters
Parameter | Description |
---|---|
x | Value 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
#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:
- A variable is initialized with a typical hyperbolic angle value.
- The
cosh()
function computes the hyperbolic cosine of the given value. - 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
#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:
- A float variable is defined with a small hyperbolic angle value.
- The
coshf()
function calculates the hyperbolic cosine for the float value. - 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
#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:
- A very large hyperbolic angle value is assigned to trigger potential overflow.
- The error number (
errno
) is reset before computation. - The
cosh()
function is called to compute the result. - The program checks if an overflow occurred by examining
errno
and prints an appropriate message.
Program Output:
Overflow occurred for cosh(1000.0)