December 2005
Beginner to intermediate
618 pages
20h 19m
English
cosh
Calculates the hyperbolic cosine of a number
#include <math.h> doublecosh( doublex); floatcoshf( floatx); (C99) long doublecoshl( long doublex); (C99)
The hyperbolic cosine of any number
x equals
(ex +
e−x)/2 and is always
greater than or equal to 1. If the result of cosh() is too great for the double type, the function incurs a range
error.
double x, sum = 1.0;
unsigned max_n;
printf("Cosh(x) is the sum as n goes from 0 to infinity "
"of x^(2*n) / (2*n)!\n");
// That's x raised to the power of 2*n, divided by 2*n factorial.
printf("Enter x and a maximum for n (separated by a space): ");
if (scanf(" %lf %u", &x, &max_n) < 2)
{
printf("Couldn't read two numbers.\n");
return -1;
}
printf("cosh(%.2f) = %.4f;\n", x,cosh(x));
for ( unsigned n = 1 ; n <= max_n ; n++ )
{
unsigned factor = 2 * n; // Calculate (2*n)!
unsigned divisor = factor;
while ( factor > 1 )
{
factor--;
divisor *= factor;
}
sum += pow(x, 2 * n) / divisor; // Accumulate the series
}
printf("Approximation by series of %u terms = %.4f.\n", max_n+1, sum);With the numbers 1.72 and 3 as input, the program produces the following output:
cosh(1.72) = 2.8818; Approximation by series of 4 terms = 2.8798.
Read now
Unlock full access