Skip to content

Commit bc5506a

Browse files
authored
Merge pull request #95 from JuliaMath/teh/float16
Prevent overflow when converting from Float16
2 parents d7ff513 + fd8e06c commit bc5506a

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

src/normed.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,11 @@ function _convert(::Type{U}, ::Type{T}, x) where {U <: Normed,T}
5050
(0 <= y) & (y <= typemax(T)) || throw_converterror(U, x)
5151
U(_unsafe_trunc(T, y), 0)
5252
end
53+
# Prevent overflow (https://discourse.julialang.org/t/saving-greater-than-8-bit-images/6057)
54+
_convert(::Type{U}, ::Type{T}, x::Float16) where {U <: Normed,T} =
55+
_convert(U, T, Float32(x))
56+
_convert(::Type{U}, ::Type{UInt128}, x::Float16) where {U <: Normed} =
57+
_convert(U, UInt128, Float32(x))
5358
function _convert(::Type{U}, ::Type{UInt128}, x) where {U <: Normed}
5459
y = round(rawone(U)*x) # for UInt128, we can't widen
5560
(0 <= y) & (y <= typemax(UInt128)) & (x <= Float64(typemax(U))) || throw_converterror(U, x)
@@ -59,6 +64,7 @@ end
5964
rem(x::T, ::Type{T}) where {T <: Normed} = x
6065
rem(x::Normed, ::Type{T}) where {T <: Normed} = reinterpret(T, _unsafe_trunc(rawtype(T), round((rawone(T)/rawone(x))*reinterpret(x))))
6166
rem(x::Real, ::Type{T}) where {T <: Normed} = reinterpret(T, _unsafe_trunc(rawtype(T), round(rawone(T)*x)))
67+
rem(x::Float16, ::Type{T}) where {T <: Normed} = rem(Float32(x), T) # avoid overflow
6268

6369
# convert(::Type{AbstractFloat}, x::Normed) = convert(floattype(x), x)
6470
float(x::Normed) = convert(floattype(x), x)

test/normed.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,3 +300,7 @@ for T in (Normed{UInt8,8}, Normed{UInt8,6},
300300
@test isa(a, Array{T,2})
301301
@test size(a) == (3,5)
302302
end
303+
304+
# Overflow with Float16
305+
@test N0f16(Float16(1.0)) === N0f16(1.0)
306+
@test Float16(1.0) % N0f16 === N0f16(1.0)

test/runtests.jl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
using FixedPointNumbers, Base.Test
22

3+
@test isempty(detect_ambiguities(FixedPointNumbers, Base, Core))
4+
35
for f in ["normed.jl", "fixed.jl"]
46
println("Testing $f")
57
include(f)
68
end
7-
8-
@test isempty(detect_ambiguities(FixedPointNumbers, Base, Core))

0 commit comments

Comments
 (0)