#include <stdint.h>
#ifdef CORE_MATH_SUPPORT_ERRNO
#include <errno.h>
#endif
#include <math.h>
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#endif
#pragma STDC FENV_ACCESS ON
typedef union {float f; uint32_t u;} b32u32_u;
static const float p0[] = {0x1.fffffcp-1, -0x1.55546cp-2, 0x1.98d0ep-3,
-0x1.0c7c54p-3};
static const float p1[] = {0x1.411612p-14, 0x1.ff076cp-1, 0x1.1ee64cp-6,
-0x1.a6fc96p-2, 0x1.81dd3ep-3};
static const float p2[] = {-0x1.95964cp-8, 0x1.0bad76p+0, -0x1.e652e2p-4,
-0x1.e70ab4p-3, 0x1.a5eb88p-4};
static const float p3[] = {-0x1.f75b16p-6, 0x1.2d3d1p+0, -0x1.882376p-2,
0x1.d18c96p-13, 0x1.6aa268p-6};
_Float16 cr_atanf16 (_Float16 x)
{
b32u32_u v = {.f = x};
uint32_t u = v.u;
uint32_t au = u & 0x7fffffffu;
#define HALF_PI 0x1.921fb6p+0f
if (au >= 0x7f800000u) { // NaN or Inf
if (au == 0x7f800000u) // +/-Inf
return (u == 0x7f800000u) ? HALF_PI : -HALF_PI;
#ifdef CORE_MATH_SUPPORT_ERRNO
errno = EDOM;
#endif
return x + x; // will signal invalid for sNaN and return qNaN
}
float t = v.f;
// for x < 0 we use atan(-x) = -atan(x)
int neg = u >> 31;
static const float Neg[] = {1.0f, -1.0f};
float s = Neg[neg];
t = t * s;
// now t >= 0
// for x > 1 we use atan(x) = pi/2 - atan(1/x)
int reduce = au > 0x3f800000u;
if (reduce) t = 1.0f / t;
// now 0 <= t <= 1
const float *p;
float y, c1, c2, c3, c5, tt = t * t;
if (t <= 0.25f) {
// for |x| < 0x1.d14p-6, atan(x) rounds to x to nearest
if (!reduce && t <= 0x1.d14p-6f) {
if (au == 0) return x; // x = 0
t = s * t;
#ifdef CORE_MATH_SUPPORT_ERRNO
/* We get underflow for |x| < 2^-14, and for |x| = 2^-14 and
rounding towards zero. */
if (au < 0x38800000 ||
(au == 0x38800000 && __builtin_fmaf (t, -0x1p-25f, t) != t))
errno = ERANGE;
#endif
return __builtin_fmaf (t, -0x1p-23f, t);
}
// deal with exceptional cases
if (au == 0x3e56a000u) // |x| = 0x1.ad4p-3
return (au == u) ? 0x1.a72002p-3f : -0x1.a72002p-3f;
if (au == 0x4115c000u) // |x| = 0x1.2b8p+3
return (au == u) ? 0x1.76dffep+0f : -0x1.76dffep+0f;
if (au == 0x42c32000u) // |x| = 0x1.864p+6
return (au == u) ? 0x1.8f7ffep+0f : -0x1.8f7ffep+0f;
p = p0;
c5 = __builtin_fmaf (p[3], tt, p[2]);
c1 = __builtin_fmaf (p[1], tt, p[0]);
c1 = __builtin_fmaf (c5, tt * tt, c1);
y = t * c1;
}
else {
p = (t <= 0.5f) ? p1 : (t <= 0.75f) ? p2 : p3;
c3 = __builtin_fmaf (p[4], t, p[3]);
c2 = __builtin_fmaf (c3, t, p[2]);
y = __builtin_fmaf (p[1], t, p[0]);
y = __builtin_fmaf (c2, tt, y);
}
if (reduce) y = HALF_PI - y;
if (neg) y = -y;
return y;
}
_Float16 atanf16 (_Float16 x) {
return (_Float16) atanf ((float) x);
}