Skip to content

Commit

Permalink
Merge pull request #50 from milankl/mk/decompose
Browse files Browse the repository at this point in the history
Base.decompose(::BFloat16)
  • Loading branch information
milankl authored Nov 6, 2023
2 parents 730511b + fe6ddca commit 9f3e1be
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/bfloat16.jl
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,17 @@ end
Base.exponent(x::BFloat16) =
((reinterpret(Unsigned, x) & Base.exponent_mask(BFloat16)) >> 7) - Base.exponent_bias(BFloat16)

function Base.decompose(x::BFloat16)::NTuple{3,Int}
isnan(x) && return 0, 0, 0
isinf(x) && return ifelse(x < 0, -1, 1), 0, 0
n = reinterpret(UInt16, x)
s = (n & 0x007f) % Int16
e = ((n & 0x7f80) >> 7) % Int
s |= Int16(e != 0) << 7
d = ifelse(signbit(x), -1, 1)
s, e - 134 + (e == 0), d
end

function Base.frexp(x::BFloat16)
xp = exponent(x) + 1
fr = significand(x) * BFloat16(0.5)
Expand Down
10 changes: 9 additions & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,15 @@ end
@test isnan(prevfloat(BFloat16s.NaNB16))
end

@testset "Decompose BFloat16" begin
for x in randn(100)
bf16 = BFloat16(x)
s,e,d = Base.decompose(bf16)
@test BFloat16(s*2.0^e/d) == bf16
end
end


@testset "Next/prevfloat(x,::Integer)" begin

x = one(BFloat16)
Expand All @@ -159,6 +168,5 @@ end
@test nextfloat(-floatmin(BFloat16),2^8) > 0
end


include("structure.jl")
include("mathfuncs.jl")

0 comments on commit 9f3e1be

Please sign in to comment.