From a0b956ccd0bbd2b7f68e9f6a27ed0270f72fa407 Mon Sep 17 00:00:00 2001 From: Erik Schnetter Date: Wed, 25 Nov 2015 15:15:17 -0500 Subject: [PATCH] Clean up mod1 Implement fld1 and fldmod1. Add test cases. Deprecate rem1. --- base/deprecated.jl | 9 +++++++++ base/exports.jl | 2 ++ base/operators.jl | 7 ++++--- test/numbers.jl | 6 ++++++ 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/base/deprecated.jl b/base/deprecated.jl index 8bcf077b5c6e38..9879c934bbc320 100644 --- a/base/deprecated.jl +++ b/base/deprecated.jl @@ -873,6 +873,15 @@ end @deprecate chol(A::Number, ::Type{Val{:L}}) ctranspose(chol(A)) @deprecate chol(A::AbstractMatrix, ::Type{Val{:L}}) ctranspose(chol(A)) +# Number updates + +# rem1 is inconsistent for x==0: The result should both have the same +# sign as x, and should be non-zero. +function rem1{T<:Real}(x::T, y::T) + depwarn("`rem1(x,y)` is discontinued, as it cannot be defined consistently for `x==0`. Rewrite the expression using `mod1` instead.", :rem1) + rem(x-1,y)+1 +end + # Filesystem module updates @deprecate_binding FS Filesystem diff --git a/base/exports.jl b/base/exports.jl index c52536c2ec3f1e..479695f953c311 100644 --- a/base/exports.jl +++ b/base/exports.jl @@ -357,7 +357,9 @@ export factor, factorial, fld, + fld1, fldmod, + fldmod1, flipsign, float, tryparse, diff --git a/base/operators.jl b/base/operators.jl index 10e5a5982abef8..076a9a6af62f6d 100644 --- a/base/operators.jl +++ b/base/operators.jl @@ -149,10 +149,11 @@ const % = rem .%(x::Real, y::Real) = x%y const รท = div -# mod returns in [0,y) whereas mod1 returns in (0,y] +# mod returns in [0,y) or (y,0] (for negative y), +# whereas mod1 returns in (0,y] or [y,0) mod1{T<:Real}(x::T, y::T) = (m=mod(x,y); ifelse(m==0, y, m)) -rem1{T<:Real}(x::T, y::T) = rem(x-1,y)+1 -fld1{T<:Real}(x::T, y::T) = fld(x-1,y)+1 +fld1{T<:Real}(x::T, y::T) = fld(x - mod1(x,y), y) +fldmod1{T<:Real}(x::T, y::T) = (m=mod1(x,y); (fld(x-m, y), m)) # transpose transpose(x) = x diff --git a/test/numbers.jl b/test/numbers.jl index db0222a942fac8..1fa3eafa657cac 100644 --- a/test/numbers.jl +++ b/test/numbers.jl @@ -2530,6 +2530,12 @@ end # test second branch, after all small primes in list have been searched @test factor(10009 * Int128(1000000000000037)) == Dict(10009=>1,1000000000000037=>1) +@test all(x -> (m=mod1(x,3); 0 x == fld1(x,3)*3 + mod1(x,3), -5:+5) +@test all(x -> fldmod1(x,3) == (fld1(x,3), mod1(x,3))) +@test all(x -> (m=mod1(x,-3); -3<=m<0), -5:+5) +@test all(x -> x == fld1(x,-3)*-3 + mod1(x,-3), -5:+5) +@test all(x -> fldmod1(x,-3) == (fld1(x,-3), mod1(x,-3))) #Issue #5570 @test map(x -> Int(mod1(UInt(x),UInt(5))), 0:15) == [5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]