Skip to content

Commit 609a4a0

Browse files
authored
fix overflow and undeflow for @fastmath exp (#42747)
Co-authored-by: oscarddssmith <oscar.smith@juliacomputing.com>
1 parent 991d6e6 commit 609a4a0

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

base/special/exp.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,8 @@ end
254254
end
255255
@inline function exp_impl_fast(x::Float64, base)
256256
T = Float64
257+
x >= MAX_EXP(base, T) && return Inf
258+
x <= -SUBNORM_EXP(base, T) && return 0.0
257259
N_float = muladd(x, LogBo256INV(base, T), MAGIC_ROUND_CONST(T))
258260
N = reinterpret(UInt64, N_float) % Int32
259261
N_float -= MAGIC_ROUND_CONST(T) #N_float now equals round(x*LogBo256INV(base, T))
@@ -288,6 +290,8 @@ end
288290

289291
@inline function exp_impl_fast(x::Float32, base)
290292
T = Float32
293+
x >= MAX_EXP(base, T) && return Inf32
294+
x <= -SUBNORM_EXP(base, T) && return 0f0
291295
N_float = round(x*LogBINV(base, T))
292296
N = unsafe_trunc(Int32, N_float)
293297
r = muladd(N_float, LogBU(base, T), x)

test/fastmath.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,3 +249,13 @@ end
249249
@test (@fastmath "a" * "b") == "ab"
250250
@test (@fastmath "a" ^ 2) == "aa"
251251
end
252+
253+
254+
@testset "exp overflow and underflow" begin
255+
for T in (Float32,Float64)
256+
for func in (@fastmath exp2,exp,exp10)
257+
@test func(T(2000)) == T(Inf)
258+
@test func(T(-2000)) == T(0)
259+
end
260+
end
261+
end

0 commit comments

Comments
 (0)