From 3bbedcad3575a3193eccec067b98e19a38a21edf Mon Sep 17 00:00:00 2001 From: Simon Byrne Date: Thu, 5 Nov 2020 13:41:26 -0800 Subject: [PATCH] Fix overflow for hypot in Float16 Fixes #38311 --- base/math.jl | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/base/math.jl b/base/math.jl index a9f259e854ee85..22c6a65d1c4bd0 100644 --- a/base/math.jl +++ b/base/math.jl @@ -661,12 +661,15 @@ function _hypot(x, y) end # Operands do not vary widely - scale = eps(typeof(ax))*sqrt(floatmin(ax)) #Rescaling constant - if ax > sqrt(floatmax(ax)/2) - ax = ax*scale - ay = ay*scale - scale = inv(scale) - elseif ay < sqrt(floatmin(ax)) + L = sqrt(floatmin(ax))/2 # a power of 2, so inv(L) is exact + if ax > inv(L) + ax = ax*L + ay = ay*L + scale = inv(L) + elseif ay < L + scale = L*eps(typeof(ax)) + # inv(scale) would underflow in Float16 + # is a power of 2, so should be optimized to a multplication by the compiler for other types ax = ax/scale ay = ay/scale else