Skip to content

Commit cd85294

Browse files
mforetslbenet
authored andcommitted
Add n-ary intersection (#257)
* Add n-ary intersection * add more tests
1 parent e6ea9c2 commit cd85294

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/intervals/set_operations.jl

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,23 @@ end
8888
intersect(a::Interval{Complex{T}}, b::Interval{Complex{S}}) where {T,S} =
8989
intersect(promote(a, b)...)
9090

91+
"""
92+
intersect(a::Interval{T}...) where T
93+
94+
Returns the n-ary intersection of its arguments.
95+
96+
This function is applicable to any number of input intervals, as in
97+
`intersect(a1, a2, a3, a4)` where `ai` is an interval.
98+
If your use case needs to splat the input, as in `intersect(a...)`, consider
99+
`reduce(intersect, a)` instead, because you save the cost of splatting.
100+
"""
101+
function intersect(a::Interval{T}...) where T
102+
low = maximum(broadcast(ai -> ai.lo, a))
103+
high = minimum(broadcast(ai -> ai.hi, a))
104+
105+
!is_valid_interval(low, high) && return emptyinterval(T)
106+
return Interval(low, high)
107+
end
91108

92109
## Hull
93110
"""

test/interval_tests/consistency.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,13 @@ setprecision(Interval, Float64)
146146

147147
@test intersect(a, hull(a,b)) == a
148148
@test union(a,b) == Interval(a.lo, b.hi)
149+
150+
# n-ary intersection
151+
@test intersect(Interval(1.0, 2.0),
152+
Interval(-1.0, 5.0),
153+
Interval(1.8, 3.0)) == Interval(1.8, 2.0)
154+
@test intersect(a, emptyinterval(), b) == emptyinterval()
155+
@test intersect(0..1, 3..4, 0..1, 0..1) == emptyinterval()
149156
end
150157

151158
@testset "Hull and union tests" begin

0 commit comments

Comments
 (0)