From fea1b3403a5682874b4d42c5c8170f67be71d582 Mon Sep 17 00:00:00 2001 From: Petr Vana Date: Tue, 24 May 2022 20:10:05 +0200 Subject: [PATCH] Introduce simplified version of mod --- src/IntervalArithmetic.jl | 1 + src/intervals/functions.jl | 10 ++++++++++ test/interval_tests/numeric.jl | 24 ++++++++++++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/src/IntervalArithmetic.jl b/src/IntervalArithmetic.jl index 0d8fc079b..19676a1ba 100644 --- a/src/IntervalArithmetic.jl +++ b/src/IntervalArithmetic.jl @@ -24,6 +24,7 @@ import Base: in, zero, one, eps, typemin, typemax, abs, abs2, real, min, max, sqrt, exp, log, sin, cos, tan, cot, inv, cbrt, csc, hypot, sec, exp2, exp10, log2, log10, + mod, asin, acos, atan, sinh, cosh, tanh, coth, csch, sech, asinh, acosh, atanh, sinpi, cospi, union, intersect, isempty, diff --git a/src/intervals/functions.jl b/src/intervals/functions.jl index 110bb41ab..731d7d2f5 100644 --- a/src/intervals/functions.jl +++ b/src/intervals/functions.jl @@ -373,3 +373,13 @@ function nthroot(a::Interval{T}, n::Integer) where T b = nthroot(bigequiv(a), n) return convert(Interval{T}, b) end + +""" +Calculate `x mod y` where `x` is an interval and `y` is a positive divisor. +""" +function mod(x::Interval, y::Real) + @assert y > 0 "modulo is currently implemented only for a positive divisor." + division = x / y + fl = floor(division) + fl.lo < fl.hi ? 0..y : y * (division - fl) +end diff --git a/test/interval_tests/numeric.jl b/test/interval_tests/numeric.jl index 3f447a5d6..8503d7ef4 100644 --- a/test/interval_tests/numeric.jl +++ b/test/interval_tests/numeric.jl @@ -434,3 +434,27 @@ end @test nthroot(Interval{BigFloat}(-81, -16), -4) == ∅ @test nthroot(Interval{BigFloat}(-81, -16), 1) == Interval{BigFloat}(-81, -16) end + +# approximation used in this testing (not to rely on ≈ for intervals) +≊(x::Interval, y::Interval) = x.lo ≈ y.lo && x.hi ≈ y.hi + +@testset "`mod`" begin + r = 0.0625 + x = r..(1+r) + @test mod(x, 1) == mod(x, 1.0) == 0..1 + @test mod(x, 2) == mod(x, 2.0) ≊ x + @test mod(x, 2.5) ≊ x + @test mod(x, 0.5) == 0..0.5 + + 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 + + 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 +end