#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[] = {1.0f, 0x1.5555fp-3f, 0x1.32b088p-4f, 0x1.8baf46p-5f};
/* degree-7 minimax polynomial for asin(x) over [0.25,0.5], with relative error
bounded by 2^-19.202, with coefficients of odd degree only, and degree-1
coefficient forced to 1. This polynomial was optimized to reduce the
number of exceptions.
*/
static const float p1[] = {0x1.000002p+0f, 0x1.55a7ep-3f, 0x1.258e54p-4f, 0x1.08e44p-4f};
#define HALF_PI 0x1.921fb4p+0f
#define HALF 0.5f
#define INV_PI 0x1.45f306p-2f
_Float16 cr_asinpif16 (_Float16 x)
{
b32u32_u v = {.f = x};
uint32_t u = v.u;
uint32_t au = u & 0x7fffffffu;
if (au >= 0x3f800000u) { // NaN, Inf, or |x| >= 1
if (au == 0x3f800000u) // |x| = 1
return (u == 0x3f800000u) ? HALF : -HALF;
#ifdef CORE_MATH_SUPPORT_ERRNO
errno = EDOM;
#endif
if ((au >> 23) == 0x3ff && ((au & 0x7fffff) != 0)) // qNaN or sNaN
return x + x;
return 0.0f / 0.0f; // will signal invalid and return sNaN
}
float t = v.f, tt, c1, c3, c5, y;
/* for |x| < 0.5 we don't reduce t into -t, since the polynomials
p0 and p1 are valid also on the negative side
int reduce = au >= 0x3f000000u; if (reduce) {
if (au == 0x3f10a000u) return (au == u) ? 0x1.876016p-3f : -0x1.876016p-3f;
if (au == 0x3f208000u) // |x|=0x1.41p-1
return (au == u) ? 0x1.b9c002p-3f : -0x1.b9c002p-3f;
if (au == 0x3f3ca000u) // |x|=0x1.794p-1
return (au == u) ? 0x1.0dfffap-2f : -0x1.0dfffap-2f;
if (u >> 31) // x < 0
t = -t;
// argument reduction: asin(x) = pi/2 - 2*asin(sqrt((1-x)/2))
t = sqrtf ((1.0f - t) * 0.5f);
b32u32_u w = {.f = t};
au = w.u & 0x7fffffffu;
}
// now 0 <= t <= 0.5
tt = t * t;
if (au < 0x3e800000u) { // 0 <= t < 0.25
/* For |x| <= 0x1.92p-13, we get underflow, except when x=0x1.92p-13
with RNDU and x=-0x1.92p-13 with RNDD.
if (au <= 0x39490000u) {
#ifdef CORE_MATH_SUPPORT_ERRNO
if (au != 0 && (au < 0x39490000u || __builtin_fmaf (t, 0x1p-25f, t) == t))
errno = ERANGE;
#endif
// INV_PI is smaller than 1/pi
return __builtin_fmaf (t, INV_PI, 0x1p-25f * t);
}
if (au == 0x3e002000) // |x| = 0x1.004p-3
return (au == u) ? 0x1.472002p-5f : -0x1.472002p-5f;
c5 = __builtin_fmaf (p0[3], tt, p0[2]); c3 = __builtin_fmaf (c5, tt, p0[1]); y = __builtin_fmaf (c3, tt * t, t);
}
else { if (au == 0x3eb7a000u) return (au == u) ? 0x1.de400ep-4f : -0x1.de400ep-4f;
if (au == 0x3ec4c000u) // |x|=0x1.898p-2
return (au == u) ? 0x1.012006p-3f : -0x1.012006p-3f;
c5 = __builtin_fmaf (p1[3], tt, p1[2]);
c1 = __builtin_fmaf (p1[1], tt, p1[0]);
y = __builtin_fmaf (c5, tt * tt, c1);
y = t * y;
}
if (reduce) {
y = HALF_PI - 2.0f * y;
if (u >> 31) y = -y;
}
return y * INV_PI;
}
_Float16 asinpif16 (_Float16 x) {
return (_Float16) asinf ((float) x) / (float) M_PI;
}