Skip to content

Commit

Permalink
define round/trunc/ceil/floor to Bool (#25085)
Browse files Browse the repository at this point in the history
(cherry picked from commit fe1264a)
  • Loading branch information
simonbyrne authored and KristofferC committed Mar 16, 2022
1 parent 6195061 commit c98d665
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
6 changes: 6 additions & 0 deletions base/float.jl
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,12 @@ floor(::Type{T}, x::AbstractFloat) where {T<:Integer} = trunc(T,round(x, RoundDo
ceil(::Type{T}, x::AbstractFloat) where {T<:Integer} = trunc(T,round(x, RoundUp))
round(::Type{T}, x::AbstractFloat) where {T<:Integer} = trunc(T,round(x, RoundNearest))

# Bool
trunc(::Type{Bool}, x::AbstractFloat) = (-1 < x < 2) ? 1 <= x : throw(InexactError(:trunc, Bool, x))
floor(::Type{Bool}, x::AbstractFloat) = (0 <= x < 2) ? 1 <= x : throw(InexactError(:floor, Bool, x))
ceil(::Type{Bool}, x::AbstractFloat) = (-1 < x <= 1) ? 0 < x : throw(InexactError(:ceil, Bool, x))
round(::Type{Bool}, x::AbstractFloat) = (-0.5 <= x < 1.5) ? 0.5 < x : throw(InexactError(:round, Bool, x))

round(x::IEEEFloat, r::RoundingMode{:ToZero}) = trunc_llvm(x)
round(x::IEEEFloat, r::RoundingMode{:Down}) = floor_llvm(x)
round(x::IEEEFloat, r::RoundingMode{:Up}) = ceil_llvm(x)
Expand Down
42 changes: 42 additions & 0 deletions test/numbers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2811,3 +2811,45 @@ end
@test_throws MethodError fld(a, b)
@test_throws MethodError cld(a, b)
end

@testset "Bool rounding (#25074)" begin
@testset "round Bool" begin
@test_throws InexactError round(Bool, -4.1)
@test_throws InexactError round(Bool, 1.5)
@test true == round(Bool, 1.0)
@test false == round(Bool, 0.0)
@test true == round(Bool, 0.6)
@test false == round(Bool, 0.4)
@test false == round(Bool, 0.5)
@test false == round(Bool, -0.5)
end

@testset "trunc Bool" begin
@test_throws InexactError trunc(Bool, -4.1)
@test_throws InexactError trunc(Bool, 2.5)
@test true == trunc(Bool, 1.0)
@test false == trunc(Bool, 0.0)
@test false == trunc(Bool, 0.6)
@test false == trunc(Bool, 0.4)
@test true == trunc(Bool, 1.8)
@test false == trunc(Bool, -0.5)
end

@testset "floor Bool" begin
@test_throws InexactError floor(Bool, -0.1)
@test_throws InexactError floor(Bool, 2.5)
@test true == floor(Bool, 1.0)
@test false == floor(Bool, 0.0)
@test false == floor(Bool, 0.6)
@test true == floor(Bool, 1.8)
end

@testset "ceil Bool" begin
@test_throws InexactError ceil(Bool, -1.4)
@test_throws InexactError ceil(Bool, 1.5)
@test true == ceil(Bool, 1.0)
@test false == ceil(Bool, 0.0)
@test true == ceil(Bool, 0.6)
@test false == ceil(Bool, -0.7)
end
end

0 comments on commit c98d665

Please sign in to comment.