#include <stdint.h>
#ifdef CORE_MATH_SUPPORT_ERRNO
#include <errno.h>
#endif
#include <fenv.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;
typedef union {double f; uint64_t u;} b64u64_u;
float cr_hypotf(float x, float y){
float ax = __builtin_fabsf(x), ay = __builtin_fabsf(y);
b32u32_u tx = {.f = ax}, ty = {.f = ay};
if(__builtin_expect(tx.u >= (0xffu<<23) || ty.u >= (0xffu<<23), 0)){
int snan_x = tx.u > (0xffu<<23) && !((tx.u >> 22) & 1);
int snan_y = ty.u > (0xffu<<23) && !((ty.u >> 22) & 1);
if (snan_x || snan_y)
return x + y; if(tx.u == (0xffu<<23)) return ax;
if(ty.u == (0xffu<<23)) return ay;
return ax + ay;
}
float at = __builtin_fmaxf(ax, ay), c;
ay = __builtin_fminf(ax, ay);
double xd = at, yd = ay, x2 = xd*xd, y2 = yd*yd, r2 = x2 + y2;
if(__builtin_expect(yd < xd*0x1.fffffep-13, 0))
{
c = __builtin_fmaf(0x1p-13f, ay, at);
#ifdef CORE_MATH_SUPPORT_ERRNO
/* If we replace v.u > 0x7f7fffffu by c > 0x1.fffffep+127,
the test fails with gcc 14.2.0 under Debian Linux.
b32u32_u v = {.f = c};
if(v.u > 0x7f7fffffu) errno = ERANGE; #endif
return c;
}
double r = __builtin_sqrt(r2);
b64u64_u t = {.f = r};
c = r;
if(t.u>(uint64_t)0x47efffffe0000000ull){ #ifdef CORE_MATH_SUPPORT_ERRNO
b32u32_u v = {.f = c};
if(v.u > 0x7f7fffffu || r >= 0x1p128) errno = ERANGE; #endif
return c;
}
if(__builtin_expect(((t.u + 1)&0xfffffff) > 2, 1)) {
#ifdef CORE_MATH_SUPPORT_ERRNO
double thres = (fegetround () == FE_TONEAREST) ? 0x1.ffffffp-127
: (fegetround () == FE_UPWARD) ? 0x1.fffffep-127
: 0x1p-126;
if (t.f < thres)
errno = ERANGE; #endif
return c;
}
double cd = c;
if((cd*cd - x2) - y2 == 0.0) return c;
double ir2 = 0.5/r2, dr2 = (x2 - r2) + y2;
double rs = r*ir2, dz = dr2 - __builtin_fma(r, r, -r2), dr = rs*dz;
double rh = r + dr, rl = dr + (r - rh);
t.f = rh;
if(__builtin_expect((t.u&0xfffffff) == 0, 1)){
if(rl>0.0) t.u += 1;
if(rl<0.0) t.u -= 1;
}
return t.f;
}