How can I define a half-open interval in Julia, and test for containment?

I’m new to Julia, and was trying to find a way to define a half-open interval like (-Inf, 5.0], then test if a floating point number is contained therein.

In Swift I could do

let leftOpenInterval = ...5.0

print(leftOpenInterval.contains(-Double.infinity)) // true
print(leftOpenInterval.contains(3)) // true
print(leftOpenInterval.contains(6)) // false
print(leftOpenInterval.contains(Double.infinity)) // false

let rightOpenInterval = 5.0...

print(rightOpenInterval.contains(-Double.infinity)) // false
print(rightOpenInterval.contains(3)) // false
print(rightOpenInterval.contains(6)) // true
print(rightOpenInterval.contains(Double.infinity)) // true

How could I achieve the equivalent result in Julia? I tried doing -Inf:5.0 and 5.0:Inf but these give me errors. Any advice on how to proceed here?

https://invenia.github.io/Intervals.jl/stable/

1 Like

Thank you for the link. However, I can’t seem to find an example of how to define the kind of unbounded interval in my OP.

If I try to mirror the example Interval{Closed,Closed}(1, 10) and try out Interval{Float64, Unbounded, Closed}(1, 5.0) or Interval{Float64, Unbounded, Closed}(5.0) (or any variation without the Float64 type annotation), I just get errors.

Is Interval{Float64,Closed,Closed}(-Inf, 5.) what you want? (-Inf..5.0 for short)

1 Like

Indeed it is. Thank you very much! :slight_smile:

IntervalSets.jl also works:

julia> using IntervalSets

julia> 5.0..Inf
5.0..Inf

julia> 6.0 ∈ 5.0..Inf
true
2 Likes

What’s the difference? When should you use one vs the other?

1 Like

Not, sure but some discussion and links here: Intervals.jl vs IntervalSets.jl?

1 Like