Skip to content

Commit 710e43d

Browse files
cfborgessimonbyrne
authored andcommitted
Correctly rounded variant of the hypot code (#32345)
* Implements the correctly rounded variant of the hypot code only in the case where there is a native FMA * Adds comments explaining the functioning of the two branches in the computation.
1 parent 6341e3e commit 710e43d

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

base/math.jl

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -579,12 +579,20 @@ function hypot(x::T,y::T) where T<:AbstractFloat
579579
scale = one(scale)
580580
end
581581
h = sqrt(muladd(ax,ax,ay*ay))
582-
if h <= 2*ay
583-
delta = h-ay
584-
h -= muladd(delta,delta-2*(ax-ay),ax*(2*delta - ax))/(2*h)
582+
# This branch is correctly rounded but requires a native hardware fma.
583+
if Base.Math.FMA_NATIVE
584+
hsquared = h*h
585+
axsquared = ax*ax
586+
h -= (fma(-ay,ay,hsquared-axsquared) + fma(h,h,-hsquared) - fma(ax,ax,-axsquared))/(2*h)
587+
# This branch is within one ulp of correctly rounded.
585588
else
586-
delta = h-ax
587-
h -= muladd(delta,delta,muladd(ay,(4*delta-ay),2*delta*(ax-2*ay)))/(2*h)
589+
if h <= 2*ay
590+
delta = h-ay
591+
h -= muladd(delta,delta-2*(ax-ay),ax*(2*delta - ax))/(2*h)
592+
else
593+
delta = h-ax
594+
h -= muladd(delta,delta,muladd(ay,(4*delta-ay),2*delta*(ax-2*ay)))/(2*h)
595+
end
588596
end
589597
h*scale
590598
end

0 commit comments

Comments
 (0)