Skip to content

Commit

Permalink
Added round method for RoundFromZero
Browse files Browse the repository at this point in the history
  • Loading branch information
jessymilare committed Sep 12, 2021
1 parent 211ed19 commit 914c4c3
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
4 changes: 4 additions & 0 deletions base/floatfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
3 changes: 1 addition & 2 deletions base/rounding.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
"""
Expand Down Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions test/rounding.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down

0 comments on commit 914c4c3

Please sign in to comment.