5
$\begingroup$

Suppose we have the interval

Interval[{-5,5}]

How do we remove an interval from within this interval?

For example, if we wanted to remove Interval[{-3,3}] from Interval[{-5,5}] we would get Interval[{-5,-3},{3,5}].

I looked in the mathematica documentations and searched through previous questions but could not find anything.

$\endgroup$
4
  • 3
    $\begingroup$ There is a function that does that in the wolfram function repository. You can use ResourceFunction["IntervalComplement"][Interval[{-5, 5}], Interval[{-3, 3}]]. $\endgroup$ Commented Aug 20, 2022 at 2:56
  • $\begingroup$ I use the wolfram website to read documentation and typing complement i found that under "Wolfram Language Documentation". I am using linux and do not have the documentation installed but maybe if you write complement in the documentation search box that function will also appear. $\endgroup$ Commented Aug 20, 2022 at 3:04
  • $\begingroup$ You can also write a custom function using IntervalMemberQ first to check whether the second interval is completely contained in the first, extract the list inside Interval using Level[Interval[{-5, 5}],{2}] and then Interval @@ Partition[Sort[{-5, 5}~Join~{-3, 3}], 2]. $\endgroup$ Commented Aug 20, 2022 at 3:13
  • 1
    $\begingroup$ Intervals are regions, RegionQ[Interval[{-5,5}]] yields True, but unfortunately RegionDifference[Interval[{-5,5}],Interval[{-3,3}]] does not return something useful. But Line works, try RegionDifference[Line[{{-5},{5}}],Line[{{-3},{3}}]], and one could translate from Interval to Line and back. $\endgroup$
    – user293787
    Commented Aug 20, 2022 at 11:01

1 Answer 1

4
$\begingroup$

The fact that this is not built-in to Mathematica suggests that there are some non-trivial subtleties. However, I offer the following simple implementation

IntervalComplement[Interval[{a_, b_}]] := 
 Interval[{-∞, a}, {b, ∞}]
IntervalComplement[Interval[a__List]] := 
 IntervalIntersection @@ IntervalComplement@*Interval /@ {a}
IntervalDifference[a_Interval, b_Interval] := 
 IntervalIntersection[a, IntervalComplement[b]]

Test cases

int1 = Interval[{-5, 5}];
int2 = Interval[{-3, 3}];
int3 = Interval[{-5, -3}, {3, 5}];
IntervalComplement /@ {int1, int2, int3}
(* {Interval[{-∞, -5}, {5, ∞}], 
 Interval[{-∞, -3}, {3, ∞}], 
 Interval[{-∞, -5}, {-3, 3}, {5, ∞}]} *)

For your example, we have

IntervalDifference[int1, int2] == int3
(* True *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.