[PATCH 3/5] newlib: libm: hypotl: avoid overflow and spurious underflow
Bernie Innocenti
bernie@codewiz.org
Sat Oct 17 09:40:36 GMT 2026
__ieee754_hypotl() computed sqrtl (x*x + y*y), which overflows when an
operand exceeds about 2^8192 (hypotl (0x1p9000L, 1) is inf) and returns
0 below about 2^-8223. Return early when the smaller operand cannot
change the result, without squaring it, and otherwise scale both by a
power of two for the 16384-exponent formats. Other formats keep the
direct formula. No new dependencies: frexpl() and ldexpl() are not
available on every target with a wide long double.
Checked on x86_64 against glibc's hypotl: 500000 random pairs over the
whole exponent range are all within 2 ulp.
Fixes: b9e7cd9a846c ("* libc/include/complex.h (cabsl): Add prototype.")
Assisted-by: Claude:claude-opus-5-5 claude-code
Signed-off-by: Bernie Innocenti <bernie@codewiz.org>
---
newlib/libm/math/el_hypot.c | 34 ++++++++++++++++++++++++++++++++--
1 file changed, 32 insertions(+), 2 deletions(-)
diff --git a/newlib/libm/math/el_hypot.c b/newlib/libm/math/el_hypot.c
index 737cde36b..e8cb86d2c 100644
--- a/newlib/libm/math/el_hypot.c
+++ b/newlib/libm/math/el_hypot.c
@@ -4,6 +4,7 @@
* is freely granted, provided that this notice is preserved.
*/
+#include <float.h>
#include "fdlibm.h"
long double
@@ -12,7 +13,36 @@ __ieee754_hypotl (long double x, long double y)
#ifdef _LDBL_EQ_DBL
return __ieee754_hypot (x, y);
#else
- /* Keep it simple for now... */
- return sqrtl ((x * x) + (y * y));
+ long double a = __builtin_fabsl (x), b = __builtin_fabsl (y), t;
+
+ if (isinf (a) || isinf (b))
+ return __builtin_infl (); /* even when the other one is a NaN */
+ if (isnan (a) || isnan (b))
+ return a + b;
+ if (a < b)
+ t = a, a = b, b = t;
+
+ /* Here b cannot change the result: do not square it, which could
+ underflow for nothing. a + b is still inexact when b is not 0. */
+ if (b <= a * LDBL_EPSILON)
+ return a + b;
+
+#if LDBL_MAX_EXP == 16384
+ /* Scale by a power of two so that neither square overflows or
+ underflows; b is within 2^LDBL_MANT_DIG of a here. */
+ if (a > 0x1p8000L)
+ {
+ a *= 0x1p-12000L;
+ b *= 0x1p-12000L;
+ return sqrtl ((a * a) + (b * b)) * 0x1p12000L;
+ }
+ if (a < 0x1p-8000L)
+ {
+ a *= 0x1p12000L;
+ b *= 0x1p12000L;
+ return sqrtl ((a * a) + (b * b)) * 0x1p-12000L;
+ }
+#endif
+ return sqrtl ((a * a) + (b * b));
#endif
}
--
2.56.0
More information about the Newlib
mailing list