From 914c4c34901de6c8578eb7f075fd780e7a72b09a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9ssica=20Milar=C3=A9?= Date: Sat, 12 Jun 2021 13:14:25 -0300 Subject: [PATCH] Added round method for RoundFromZero --- base/floatfuncs.jl | 4 ++++ base/rounding.jl | 3 +-- test/rounding.jl | 15 +++++++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/base/floatfuncs.jl b/base/floatfuncs.jl index bae27d642e7c7..30c4033512d2b 100644 --- a/base/floatfuncs.jl +++ b/base/floatfuncs.jl @@ -236,6 +236,10 @@ function round(x::T, ::RoundingMode{:NearestTiesUp}) where {T <: AbstractFloat} copysign(floor((x + (T(0.25) - eps(T(0.5)))) + (T(0.25) + eps(T(0.5)))), x) end +function Base.round(x::AbstractFloat, ::typeof(RoundFromZero)) + signbit(x) ? round(x, RoundDown) : round(x, RoundUp) +end + # isapprox: approximate equality of numbers """ isapprox(x, y; atol::Real=0, rtol::Real=atol>0 ? 0 : √eps, nans::Bool=false[, norm::Function]) diff --git a/base/rounding.jl b/base/rounding.jl index bf29d8b54602e..341fdb4495a42 100644 --- a/base/rounding.jl +++ b/base/rounding.jl @@ -37,7 +37,7 @@ Currently supported rounding modes are: - [`RoundNearestTiesAway`](@ref) - [`RoundNearestTiesUp`](@ref) - [`RoundToZero`](@ref) -- [`RoundFromZero`](@ref) ([`BigFloat`](@ref) only) +- [`RoundFromZero`](@ref) - [`RoundUp`](@ref) - [`RoundDown`](@ref) """ @@ -76,7 +76,6 @@ const RoundDown = RoundingMode{:Down}() RoundFromZero Rounds away from zero. -This rounding mode may only be used with `T == BigFloat` inputs to [`round`](@ref). # Examples ```jldoctest diff --git a/test/rounding.jl b/test/rounding.jl index e4c51212e81fa..0fe1513c6c450 100644 --- a/test/rounding.jl +++ b/test/rounding.jl @@ -128,6 +128,16 @@ end else @test u === r end + + r = round(u, RoundFromZero) + if isfinite(u) + @test isfinite(r) + @test isinteger(r) + @test signbit(u) ? (r == floor(u)) : (r == ceil(u)) + @test signbit(u) == signbit(r) + else + @test u === r + end end end end @@ -171,6 +181,7 @@ end @test round.(y) ≈ t[(i+1+isodd(i>>2))>>2 for i in r] @test broadcast(x -> round(x, RoundNearestTiesAway), y) ≈ t[(i+1+(i>=0))>>2 for i in r] @test broadcast(x -> round(x, RoundNearestTiesUp), y) ≈ t[(i+2)>>2 for i in r] + @test broadcast(x -> round(x, RoundFromZero), y) ≈ t[(i+3*(i>=0))>>2 for i in r] end end end @@ -190,6 +201,10 @@ end @test round(Int,-2.5,RoundNearestTiesUp) == -2 @test round(Int,-1.5,RoundNearestTiesUp) == -1 @test round(Int,-1.9) == -2 + @test round(Int,nextfloat(1.0),RoundFromZero) == 2 + @test round(Int,-nextfloat(1.0),RoundFromZero) == -2 + @test round(Int,prevfloat(1.0),RoundFromZero) == 1 + @test round(Int,-prevfloat(1.0),RoundFromZero) == -1 @test_throws InexactError round(Int64, 9.223372036854776e18) @test round(Int64, 9.223372036854775e18) == 9223372036854774784 @test_throws InexactError round(Int64, -9.223372036854778e18)