initial cmath code and minor libm.h update
[libm] / src / math / cosh.c
1 /* origin: FreeBSD /usr/src/lib/msun/src/e_cosh.c */
2 /*
3  * ====================================================
4  * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
5  *
6  * Developed at SunSoft, a Sun Microsystems, Inc. business.
7  * Permission to use, copy, modify, and distribute this
8  * software is freely granted, provided that this notice
9  * is preserved.
10  * ====================================================
11  */
12 /* cosh(x)
13  * Method :
14  * mathematically cosh(x) if defined to be (exp(x)+exp(-x))/2
15  *      1. Replace x by |x| (cosh(x) = cosh(-x)).
16  *      2.
17  *                                                      [ exp(x) - 1 ]^2
18  *          0        <= x <= ln2/2  :  cosh(x) := 1 + -------------------
19  *                                                         2*exp(x)
20  *
21  *                                                exp(x) +  1/exp(x)
22  *          ln2/2    <= x <= 22     :  cosh(x) := -------------------
23  *                                                        2
24  *          22       <= x <= lnovft :  cosh(x) := exp(x)/2
25  *          lnovft   <= x <= ln2ovft:  cosh(x) := exp(x/2)/2 * exp(x/2)
26  *          ln2ovft  <  x           :  cosh(x) := huge*huge (overflow)
27  *
28  * Special cases:
29  *      cosh(x) is |x| if x is +INF, -INF, or NaN.
30  *      only cosh(0)=1 is exact for finite x.
31  */
32
33 #include "libm.h"
34
35 static const double one = 1.0, half = 0.5, huge = 1.0e300;
36
37 double cosh(double x)
38 {
39         double t, w;
40         int32_t ix;
41
42         GET_HIGH_WORD(ix, x);
43         ix &= 0x7fffffff;
44
45         /* x is INF or NaN */
46         if (ix >= 0x7ff00000)
47                 return x*x;
48
49         /* |x| in [0,0.5*ln2], return 1+expm1(|x|)^2/(2*exp(|x|)) */
50         if (ix < 0x3fd62e43) {
51                 t = expm1(fabs(x));
52                 w = one+t;
53                 if (ix < 0x3c800000)
54                         return w;  /* cosh(tiny) = 1 */
55                 return one + (t*t)/(w+w);
56         }
57
58         /* |x| in [0.5*ln2,22], return (exp(|x|)+1/exp(|x|)/2; */
59         if (ix < 0x40360000) {
60                 t = exp(fabs(x));
61                 return half*t + half/t;
62         }
63
64         /* |x| in [22, log(maxdouble)] return half*exp(|x|) */
65         if (ix < 0x40862E42)
66                 return half*exp(fabs(x));
67
68         /* |x| in [log(maxdouble), overflowthresold] */
69         if (ix<=0x408633CE)
70                 return __ldexp_exp(fabs(x), -1);
71
72         /* |x| > overflowthresold, cosh(x) overflow */
73         return huge*huge;
74 }