1/*
2 * Double-precision acosh(x) function.
3 *
4 * Copyright (c) 2022-2023, Arm Limited.
5 * SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception
6 */
7
8#include "math_config.h"
9#include "pl_sig.h"
10#include "pl_test.h"
11
12#define Ln2 (0x1.62e42fefa39efp-1)
13#define MinusZero (0x8000000000000000)
14#define SquareLim (0x5fe0000000000000) /* asuint64(0x1.0p511).  */
15#define Two (0x4000000000000000)       /* asuint64(2.0).  */
16
17double
18optr_aor_log_f64 (double);
19
20double
21log1p (double);
22
23/* acosh approximation using a variety of approaches on different intervals:
24
25   acosh(x) = ln(x + sqrt(x * x - 1)).
26
27   x >= 2^511: We cannot square x without overflow. For huge x, sqrt(x*x - 1) is
28   close enough to x that we can calculate the result by ln(2x) == ln(x) +
29   ln(2). The greatest observed error in this region is 0.98 ULP:
30   acosh(0x1.1b9bf42923d1dp+853) got 0x1.28066a11a7c7fp+9
31				want 0x1.28066a11a7c8p+9.
32
33   x > 2: Calculate the result directly using definition of acosh(x). Greatest
34   observed error in this region is 1.33 ULP:
35   acosh(0x1.1e45d14bfcfa2p+1) got 0x1.71a06f50c34b5p+0
36			      want 0x1.71a06f50c34b6p+0.
37
38   0 <= x <= 2: Calculate the result using log1p. For x < 1, acosh(x) is
39   undefined. For 1 <= x <= 2, the largest observed error is 2.69 ULP:
40   acosh(0x1.073528248093p+0) got 0x1.e4d9bd20684f3p-3
41			     want 0x1.e4d9bd20684f6p-3.  */
42double
43acosh (double x)
44{
45  uint64_t ix = asuint64 (x);
46
47  if (unlikely (ix >= MinusZero))
48    return __math_invalid (x);
49
50  if (unlikely (ix >= SquareLim))
51    return optr_aor_log_f64 (x) + Ln2;
52
53  if (ix >= Two)
54    return optr_aor_log_f64 (x + sqrt (x * x - 1));
55
56  double xm1 = x - 1;
57  return log1p (xm1 + sqrt (2 * xm1 + xm1 * xm1));
58}
59
60PL_SIG (S, D, 1, acosh, 1.0, 10.0)
61PL_TEST_ULP (acosh, 2.19)
62PL_TEST_INTERVAL (acosh, 0, 1, 10000)
63PL_TEST_INTERVAL (acosh, 1, 2, 100000)
64PL_TEST_INTERVAL (acosh, 2, 0x1p511, 100000)
65PL_TEST_INTERVAL (acosh, 0x1p511, inf, 100000)
66PL_TEST_INTERVAL (acosh, -0, -inf, 10000)
67