diff --git a/base/math.jl b/base/math.jl index 875a2be7d19982..19ed2bbb4e13dd 100644 --- a/base/math.jl +++ b/base/math.jl @@ -629,9 +629,19 @@ julia> hypot(3, 4im) hypot(x::Number, y::Number) = hypot(promote(x, y)...) hypot(x::Complex, y::Complex) = hypot(abs(x), abs(y)) hypot(x::T, y::T) where {T<:Real} = hypot(float(x), float(y)) -hypot(x::T, y::T) where {T<:Number} = (z = y/x; abs(x) * sqrt(one(z) + z*z)) +function hypot(x::T, y::T) where {T<:Number} + if !iszero(x) + z = y/x + z2 = z*z + + abs(x) * sqrt(oneunit(z2) + z2) + else + abs(y) + end +end + function hypot(x::T, y::T) where T<:AbstractFloat - #Return Inf if either or both imputs is Inf (Compliance with IEEE754) + # Return Inf if either or both inputs is Inf (Compliance with IEEE754) if isinf(x) || isinf(y) return T(Inf) end diff --git a/test/math.jl b/test/math.jl index 22d7f91685a0a3..382c84f4dd6558 100644 --- a/test/math.jl +++ b/test/math.jl @@ -1035,10 +1035,15 @@ end end end -isdefined(Main, :Furlongs) || @eval Main include("testhelpers/Furlongs.jl") -using .Main.Furlongs -@test hypot(Furlong(0), Furlong(0)) == Furlong(0.0) -@test hypot(Furlong(3), Furlong(4)) == Furlong(5.0) -@test hypot(Furlong(NaN), Furlong(Inf)) == Furlong(Inf) -@test hypot(Furlong(Inf), Furlong(NaN)) == Furlong(Inf) -@test hypot(Furlong(Inf), Furlong(Inf)) == Furlong(Inf) +@testset "hypot" begin + @test hypot(0, 0) == 0.0 + @test hypot(3, 4) == 5.0 + @test hypot(NaN, Inf) == Inf + @test hypot(Inf, NaN) == Inf + @test hypot(Inf, Inf) == Inf + + isdefined(Main, :Furlongs) || @eval Main include("testhelpers/Furlongs.jl") + using .Main.Furlongs + @test hypot(Furlong(0), Furlong(0)) == Furlong(0.0) + @test hypot(Furlong(3), Furlong(4)) == Furlong(5.0) +end diff --git a/test/testhelpers/Furlongs.jl b/test/testhelpers/Furlongs.jl index d9a0226c0ee9d0..20b9ae89ac0000 100644 --- a/test/testhelpers/Furlongs.jl +++ b/test/testhelpers/Furlongs.jl @@ -46,8 +46,8 @@ for f in (:real,:imag,:complex,:+,:-) @eval Base.$f(x::Furlong{p}) where {p} = Furlong{p}($f(x.val)) end -import Base: +, -, ==, !=, <, <=, isless, isequal, *, /, //, div, rem, mod, ^, hypot -for op in (:+, :-, :hypot) +import Base: +, -, ==, !=, <, <=, isless, isequal, *, /, //, div, rem, mod, ^ +for op in (:+, :-) @eval function $op(x::Furlong{p}, y::Furlong{p}) where {p} v = $op(x.val, y.val) Furlong{p}(v)