math: cosh cleanup
[musl] / 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) := inf (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 double cosh(double x)
36 {
37         union {double f; uint64_t i;} u = {.f = x};
38         uint32_t ix;
39         double t;
40
41         /* |x| */
42         u.i &= (uint64_t)-1/2;
43         x = u.f;
44         ix = u.i >> 32;
45
46         /* |x| in [0,0.5*ln2], return 1+expm1(|x|)^2/(2*exp(|x|)) */
47         if (ix < 0x3fd62e43) {
48                 t = expm1(x);
49                 if (ix < 0x3c800000)
50                         return 1;
51                 return 1 + t*t/(2*(1+t));
52         }
53
54         /* |x| in [0.5*ln2,22], return (exp(|x|)+1/exp(|x|))/2; */
55         if (ix < 0x40360000) {
56                 t = exp(x);
57                 return 0.5*t + 0.5/t;
58         }
59
60         /* |x| in [22, log(maxdouble)] return 0.5*exp(|x|) */
61         if (ix < 0x40862e42)
62                 return 0.5*exp(x);
63
64         /* |x| in [log(maxdouble), overflowthresold] */
65         if (ix <= 0x408633ce)
66                 return __expo2(x);
67
68         /* overflow (or nan) */
69         x *= 0x1p1023;
70         return x;
71 }