1 /*
2  * Single-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 "atanf_common.h"
15 
16 #define PiOver2 v_f32 (0x1.921fb6p+0f)
17 #define AbsMask v_u32 (0x7fffffff)
18 #define TinyBound 0x308 /* top12(asuint(0x1p-30)).  */
19 #define BigBound 0x4e8	/* top12(asuint(0x1p30)).  */
20 
21 #if WANT_SIMD_EXCEPT
22 static NOINLINE v_f32_t
23 specialcase (v_f32_t x, v_f32_t y, v_u32_t special)
24 {
25   return v_call_f32 (atanf, x, y, special);
26 }
27 #endif
28 
29 /* Fast implementation of vector atanf based on
30    atan(x) ~ shift + z + z^3 * P(z^2) with reduction to [0,1]
31    using z=-1/x and shift = pi/2. Maximum observed error is 2.9ulps:
32    v_atanf(0x1.0468f6p+0) got 0x1.967f06p-1 want 0x1.967fp-1.  */
33 VPCS_ATTR
34 v_f32_t V_NAME (atanf) (v_f32_t x)
35 {
36   /* Small cases, infs and nans are supported by our approximation technique,
37      but do not set fenv flags correctly. Only trigger special case if we need
38      fenv.  */
39   v_u32_t ix = v_as_u32_f32 (x);
40   v_u32_t sign = ix & ~AbsMask;
41 
42 #if WANT_SIMD_EXCEPT
43   v_u32_t ia12 = (ix >> 20) & 0x7ff;
44   v_u32_t special = v_cond_u32 (ia12 - TinyBound > BigBound - TinyBound);
45   /* If any lane is special, fall back to the scalar routine for all lanes.  */
46   if (unlikely (v_any_u32 (special)))
47     return specialcase (x, x, v_u32 (-1));
48 #endif
49 
50   /* Argument reduction:
51      y := arctan(x) for x < 1
52      y := pi/2 + arctan(-1/x) for x > 1
53      Hence, use z=-1/a if x>=1, otherwise z=a.  */
54   v_u32_t red = v_cagt_f32 (x, v_f32 (1.0));
55   /* Avoid dependency in abs(x) in division (and comparison).  */
56   v_f32_t z = v_sel_f32 (red, v_div_f32 (v_f32 (-1.0f), x), x);
57   v_f32_t shift = v_sel_f32 (red, PiOver2, v_f32 (0.0f));
58   /* Use absolute value only when needed (odd powers of z).  */
59   v_f32_t az = v_abs_f32 (z);
60   az = v_sel_f32 (red, -az, az);
61 
62   /* Calculate the polynomial approximation.  */
63   v_f32_t y = eval_poly (z, az, shift);
64 
65   /* y = atan(x) if x>0, -atan(-x) otherwise.  */
66   y = v_as_f32_u32 (v_as_u32_f32 (y) ^ sign);
67 
68   return y;
69 }
70 VPCS_ALIAS
71 
72 PL_SIG (V, F, 1, atan, -10.0, 10.0)
73 PL_TEST_ULP (V_NAME (atanf), 2.5)
74 PL_TEST_EXPECT_FENV (V_NAME (atanf), WANT_SIMD_EXCEPT)
75 PL_TEST_INTERVAL (V_NAME (atanf), 0, 0x1p-30, 5000)
76 PL_TEST_INTERVAL (V_NAME (atanf), -0, -0x1p-30, 5000)
77 PL_TEST_INTERVAL (V_NAME (atanf), 0x1p-30, 1, 40000)
78 PL_TEST_INTERVAL (V_NAME (atanf), -0x1p-30, -1, 40000)
79 PL_TEST_INTERVAL (V_NAME (atanf), 1, 0x1p30, 40000)
80 PL_TEST_INTERVAL (V_NAME (atanf), -1, -0x1p30, 40000)
81 PL_TEST_INTERVAL (V_NAME (atanf), 0x1p30, inf, 1000)
82 PL_TEST_INTERVAL (V_NAME (atanf), -0x1p30, -inf, 1000)
83 #endif
84