1 /*
2  * Double-precision vector atan(x) function.
3  *
4  * Copyright (c) 2021-2023, Arm Limited.
5  * SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception
6  */
7 
8 #include "v_math.h"
9 #include "pl_sig.h"
10 #include "pl_test.h"
11 
12 #if V_SUPPORTED
13 
14 #include "atan_common.h"
15 
16 #define PiOver2 v_f64 (0x1.921fb54442d18p+0)
17 #define AbsMask v_u64 (0x7fffffffffffffff)
18 #define TinyBound 0x3e1 /* top12(asuint64(0x1p-30)).  */
19 #define BigBound 0x434	/* top12(asuint64(0x1p53)).  */
20 
21 /* Fast implementation of vector atan.
22    Based on atan(x) ~ shift + z + z^3 * P(z^2) with reduction to [0,1] using
23    z=1/x and shift = pi/2. Maximum observed error is 2.27 ulps:
24    __v_atan(0x1.0005af27c23e9p+0) got 0x1.9225645bdd7c1p-1
25 				 want 0x1.9225645bdd7c3p-1.  */
26 VPCS_ATTR
27 v_f64_t V_NAME (atan) (v_f64_t x)
28 {
29   /* Small cases, infs and nans are supported by our approximation technique,
30      but do not set fenv flags correctly. Only trigger special case if we need
31      fenv.  */
32   v_u64_t ix = v_as_u64_f64 (x);
33   v_u64_t sign = ix & ~AbsMask;
34 
35 #if WANT_SIMD_EXCEPT
36   v_u64_t ia12 = (ix >> 52) & 0x7ff;
37   v_u64_t special = v_cond_u64 (ia12 - TinyBound > BigBound - TinyBound);
38   /* If any lane is special, fall back to the scalar routine for all lanes.  */
39   if (unlikely (v_any_u64 (special)))
40     return v_call_f64 (atan, x, v_f64 (0), v_u64 (-1));
41 #endif
42 
43   /* Argument reduction:
44      y := arctan(x) for x < 1
45      y := pi/2 + arctan(-1/x) for x > 1
46      Hence, use z=-1/a if x>=1, otherwise z=a.  */
47   v_u64_t red = v_cagt_f64 (x, v_f64 (1.0));
48   /* Avoid dependency in abs(x) in division (and comparison).  */
49   v_f64_t z = v_sel_f64 (red, v_div_f64 (v_f64 (-1.0), x), x);
50   v_f64_t shift = v_sel_f64 (red, PiOver2, v_f64 (0.0));
51   /* Use absolute value only when needed (odd powers of z).  */
52   v_f64_t az = v_abs_f64 (z);
53   az = v_sel_f64 (red, -az, az);
54 
55   /* Calculate the polynomial approximation.  */
56   v_f64_t y = eval_poly (z, az, shift);
57 
58   /* y = atan(x) if x>0, -atan(-x) otherwise.  */
59   y = v_as_f64_u64 (v_as_u64_f64 (y) ^ sign);
60   return y;
61 }
62 VPCS_ALIAS
63 
64 PL_SIG (V, D, 1, atan, -10.0, 10.0)
65 PL_TEST_ULP (V_NAME (atan), 1.78)
66 PL_TEST_EXPECT_FENV (V_NAME (atan), WANT_SIMD_EXCEPT)
67 PL_TEST_INTERVAL (V_NAME (atan), 0, 0x1p-30, 10000)
68 PL_TEST_INTERVAL (V_NAME (atan), -0, -0x1p-30, 1000)
69 PL_TEST_INTERVAL (V_NAME (atan), 0x1p-30, 0x1p53, 900000)
70 PL_TEST_INTERVAL (V_NAME (atan), -0x1p-30, -0x1p53, 90000)
71 PL_TEST_INTERVAL (V_NAME (atan), 0x1p53, inf, 10000)
72 PL_TEST_INTERVAL (V_NAME (atan), -0x1p53, -inf, 1000)
73 
74 #endif
75