Skip to content

Commit 448072f

Browse files
oscardssmithoscarddssmith
authored andcommitted
fix overflow and undeflow for @fastmath exp (#42747)
Co-authored-by: oscarddssmith <oscar.smith@juliacomputing.com> (cherry picked from commit 609a4a0)
1 parent f4df914 commit 448072f

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
@@ -227,6 +227,8 @@ end
227227
end
228228
@inline function exp_impl_fast(x::Float64, base)
229229
T = Float64
230+
x >= MAX_EXP(base, T) && return Inf
231+
x <= -SUBNORM_EXP(base, T) && return 0.0
230232
N_float = muladd(x, LogBo256INV(base, T), MAGIC_ROUND_CONST(T))
231233
N = reinterpret(UInt64, N_float) % Int32
232234
N_float -= MAGIC_ROUND_CONST(T) #N_float now equals round(x*LogBo256INV(base, T))
@@ -261,6 +263,8 @@ end
261263

262264
@inline function exp_impl_fast(x::Float32, base)
263265
T = Float32
266+
x >= MAX_EXP(base, T) && return Inf32
267+
x <= -SUBNORM_EXP(base, T) && return 0f0
264268
N_float = round(x*LogBINV(base, T))
265269
N = unsafe_trunc(Int32, N_float)
266270
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)