diff --git a/src/intervals/functions.jl b/src/intervals/functions.jl index 5ea1cf59d..588b163d7 100644 --- a/src/intervals/functions.jl +++ b/src/intervals/functions.jl @@ -375,13 +375,18 @@ function nthroot(a::Interval{T}, n::Integer) where T end """ -Calculate `x mod y` where `x` is an interval and `y` is a positive divisor. +Calculate `x::Interval mod y::Real`, limited by `y != 0`. """ function mod(x::Interval, y::Real) - @assert y > zero(y) "modulo is currently implemented only for a positive divisor." + @assert y != zero(y) """mod(x::Interval, y::Real) +is currently implemented only for a strictly positive or negative divisor y.""" division = x / y fl = floor(division) - fl.lo < fl.hi ? Interval(zero(y), y) : y * (division - fl) + if !isthin(fl) + return y > zero(y) ? Interval(zero(y), y) : Interval(y, zero(y)) + else + return y * (division - fl) + end end mod(x:T, y::Interval) where T = throw(ArgumentError("mod not defined for interval as divisor `y`")) diff --git a/test/interval_tests/numeric.jl b/test/interval_tests/numeric.jl index 3d88a91a0..d933f9c7c 100644 --- a/test/interval_tests/numeric.jl +++ b/test/interval_tests/numeric.jl @@ -446,18 +446,31 @@ end @test mod(x, 2) == mod(x, 2.0) ⪆ x @test mod(x, 2.5) ⪆ x @test mod(x, 0.5) == 0..0.5 + @test mod(x, -1) == mod(x, -1.0) == -1..0 + @test mod(x, -2) == mod(x, -2.0) ⪆ -2+x + @test mod(x, -2.5) ⪆ -2.5+x + @test mod(x, -0.5) == -0.5..0 x = (-1+r) .. -r @test mod(x, 1) == mod(x, 1.0) ⪆ 1+x @test mod(x, 2) == mod(x, 2.0) ⪆ 2+x @test mod(x, 2.5) ⪆ 2.5+x @test mod(x, 0.5) == 0..0.5 + @test mod(x, -1) == mod(x, -1.0) ⪆ x + @test mod(x, -2) == mod(x, -2.0) ⪆ x + @test mod(x, -2.5) ⪆ x + @test mod(x, -0.5) == -0.5..0 x = -r .. 1-r @test mod(x, 1) == mod(x, 1.0) == 0..1 @test mod(x, 2) == mod(x, 2.0) == 0..2 @test mod(x, 2.5) == 0..2.5 @test mod(x, 0.5) == 0..0.5 + @test mod(x, -1) == mod(x, -1.0) == -1..0 + @test mod(x, -2) == mod(x, -2.0) == -2..0 + @test mod(x, -2.5) == -2.5..0 + @test mod(x, -0.5) == -0.5..0 - @test_throws AssertionError mod(x, -1) + # TODO - implement mod for two intervals + @test_throws TypeError mod(1..2, 1.4..1.5) end