1 /*
2 * Single-precision cosh(x) function.
3 *
4 * Copyright (c) 2022-2024, Arm Limited.
5 * SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception
6 */
7
8 #include "mathlib.h"
9 #include "math_config.h"
10 #include "test_sig.h"
11 #include "test_defs.h"
12
13 #define AbsMask 0x7fffffff
14 #define TinyBound 0x20000000 /* 0x1p-63: Round to 1 below this. */
15 /* 0x1.5a92d8p+6: expf overflows above this, so have to use special case. */
16 #define SpecialBound 0x42ad496c
17
18 static NOINLINE float
specialcase(float x,uint32_t iax)19 specialcase (float x, uint32_t iax)
20 {
21 if (iax == 0x7f800000)
22 return INFINITY;
23 if (iax > 0x7f800000)
24 return __math_invalidf (x);
25 if (iax <= TinyBound)
26 /* For tiny x, avoid underflow by just returning 1. */
27 return 1;
28 /* Otherwise SpecialBound <= |x| < Inf. x is too large to calculate exp(x)
29 without overflow, so use exp(|x|/2) instead. For large x cosh(x) is
30 dominated by exp(x), so return:
31 cosh(x) ~= (exp(|x|/2))^2 / 2. */
32 float t = expf (asfloat (iax) / 2);
33 return (0.5 * t) * t;
34 }
35
36 /* Approximation for single-precision cosh(x) using exp.
37 cosh(x) = (exp(x) + exp(-x)) / 2.
38 The maximum error is 1.89 ULP, observed for |x| > SpecialBound:
39 coshf(0x1.65898cp+6) got 0x1.f00aep+127 want 0x1.f00adcp+127.
40 The maximum error observed for TinyBound < |x| < SpecialBound is 1.02 ULP:
41 coshf(0x1.50a3cp+0) got 0x1.ff21dcp+0 want 0x1.ff21dap+0. */
42 float
coshf(float x)43 coshf (float x)
44 {
45 uint32_t ix = asuint (x);
46 uint32_t iax = ix & AbsMask;
47 float ax = asfloat (iax);
48
49 if (unlikely (iax <= TinyBound || iax >= SpecialBound))
50 {
51 /* x is tiny, large or special. */
52 return specialcase (x, iax);
53 }
54
55 /* Compute cosh using the definition:
56 coshf(x) = exp(x) / 2 + exp(-x) / 2. */
57 float t = expf (ax);
58 return 0.5f * t + 0.5f / t;
59 }
60
61 TEST_SIG (S, F, 1, cosh, -10.0, 10.0)
62 TEST_ULP (coshf, 1.89)
63 TEST_SYM_INTERVAL (coshf, 0, 0x1p-63, 100)
64 TEST_SYM_INTERVAL (coshf, 0, 0x1.5a92d8p+6, 80000)
65 TEST_SYM_INTERVAL (coshf, 0x1.5a92d8p+6, inf, 2000)
66