Skip to content

fix overflow and undeflow for @fastmath exp #42747

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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