Skip to content

Commit 7715b68

Browse files
authored
Convert NaN to correct type in sqrt (#64)
* Convert NaN to correct type in sqrt * Split sqrt into AbstractFloat and Real case
1 parent 65a5928 commit 7715b68

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

src/NaNMath.jl

+2-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ end
1414

1515
# Would be more efficient to remove the domain check in Base.sqrt(),
1616
# but this doesn't seem easy to do.
17-
sqrt(x::Real) = x < 0.0 ? NaN : Base.sqrt(x)
17+
sqrt(x::T) where {T<:AbstractFloat} = x < 0.0 ? T(NaN) : Base.sqrt(x)
18+
sqrt(x::Real) = sqrt(float(x))
1819

1920
# Don't override built-in ^ operator
2021
pow(x::Float64, y::Float64) = ccall((:pow,libm), Float64, (Float64,Float64), x, y)

test/runtests.jl

+9
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,15 @@ using Test
1818
@test NaNMath.pow(-1.5,2.3) isa Float64
1919
@test isnan(NaNMath.sqrt(-5))
2020
@test NaNMath.sqrt(5) == Base.sqrt(5)
21+
@test isnan(NaNMath.sqrt(-3.2f0)) && NaNMath.sqrt(-3.2f0) isa Float32
22+
@test isnan(NaNMath.sqrt(-BigFloat(7.0))) && NaNMath.sqrt(-BigFloat(7.0)) isa BigFloat
23+
@test isnan(NaNMath.sqrt(-7)) && NaNMath.sqrt(-7) isa Float64
24+
@inferred NaNMath.sqrt(5)
25+
@inferred NaNMath.sqrt(5.0)
26+
@inferred NaNMath.sqrt(5.0f0)
27+
@inferred NaNMath.sqrt(-5)
28+
@inferred NaNMath.sqrt(-5.0)
29+
@inferred NaNMath.sqrt(-5.0f0)
2130
@test NaNMath.sum([1., 2., NaN]) == 3.0
2231
@test NaNMath.sum([1. 2.; NaN 1.]) == 4.0
2332
@test isnan(NaNMath.sum([NaN, NaN]))

0 commit comments

Comments
 (0)