Skip to content

Commit

Permalink
fix overflow and undeflow for @fastmath exp (#42747)
Browse files Browse the repository at this point in the history
Co-authored-by: oscarddssmith <oscar.smith@juliacomputing.com>
  • Loading branch information
oscardssmith and oscardssmith authored Oct 22, 2021
1 parent 991d6e6 commit 609a4a0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
4 changes: 4 additions & 0 deletions base/special/exp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,8 @@ end
end
@inline function exp_impl_fast(x::Float64, base)
T = Float64
x >= MAX_EXP(base, T) && return Inf
x <= -SUBNORM_EXP(base, T) && return 0.0
N_float = muladd(x, LogBo256INV(base, T), MAGIC_ROUND_CONST(T))
N = reinterpret(UInt64, N_float) % Int32
N_float -= MAGIC_ROUND_CONST(T) #N_float now equals round(x*LogBo256INV(base, T))
Expand Down Expand Up @@ -288,6 +290,8 @@ end

@inline function exp_impl_fast(x::Float32, base)
T = Float32
x >= MAX_EXP(base, T) && return Inf32
x <= -SUBNORM_EXP(base, T) && return 0f0
N_float = round(x*LogBINV(base, T))
N = unsafe_trunc(Int32, N_float)
r = muladd(N_float, LogBU(base, T), x)
Expand Down
10 changes: 10 additions & 0 deletions test/fastmath.jl
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,13 @@ end
@test (@fastmath "a" * "b") == "ab"
@test (@fastmath "a" ^ 2) == "aa"
end


@testset "exp overflow and underflow" begin
for T in (Float32,Float64)
for func in (@fastmath exp2,exp,exp10)
@test func(T(2000)) == T(Inf)
@test func(T(-2000)) == T(0)
end
end
end

0 comments on commit 609a4a0

Please sign in to comment.