6
$\begingroup$

I have two sets $A = \{1 \leq x \leq 5\}$ and $B = \{5 \leq x \leq 8\}$. Now I want to find the Union and Intersection of $A$ and $B$.

I tried Union[A, B], I got {1 <= x <= 5, 5 <= x <= 8} and for Intersection[A, B], I got {}. The correct answer for $A \cup B$ is [1, 8] and $A \cap B$ is {5}. How do I tell Mathematica to do that?

And if $A = \{1 < x < 5\}$ and $B = \{x > 5\}$. Now I want to find the Union and Intersection of $A$ and $B$. How do I tell Mathematica to do that?

$\endgroup$
1
  • 1
    $\begingroup$ You will want to use Interval. $\endgroup$
    – DavidC
    Oct 1, 2012 at 1:13

2 Answers 2

10
$\begingroup$
a = Interval[{1, 5}];
b = Interval[{5, 8}];
IntervalUnion[a, b]

Interval[{1, 8}]

IntervalIntersection[a, b]

Interval[{5, 5}]

$\endgroup$
13
  • 2
    $\begingroup$ Interval[{1,5},{5,8}] also gives IntervalUnion[a,b] (+1) $\endgroup$
    – kglr
    Oct 1, 2012 at 1:28
  • $\begingroup$ Nice. I wasn't aware of that. $\endgroup$
    – DavidC
    Oct 1, 2012 at 1:30
  • $\begingroup$ If A = {1 < x < 5} and B = {x > 1}. How must I do? $\endgroup$ Oct 1, 2012 at 1:45
  • 1
    $\begingroup$ @minthao: B = Interval[{1, ∞}]. $\endgroup$ Oct 1, 2012 at 1:52
  • 1
    $\begingroup$ @minthao. Mathematica seems to work only with closed intervals. Interval[{1,5] includes the numbers 1 and 5, and therefore does not match your original inequality, 1<x<5. I don't know whether there is a way to not include the end points. Perhaps this is a question worth asking. $\endgroup$
    – DavidC
    Oct 1, 2012 at 2:31
2
$\begingroup$

Open/closed intervals compatible with regions:

OpenInterval[a_, b_] := ImplicitRegion[a < x && x < b, {x}];
ClosedInterval[a_, b_] := ImplicitRegion[a <= x && x <= b, {x}];

Semi-open intervals and infinity intervals are similar.

Need some typing to transform region to an expression:

  • open intervals:
    RegionMember[RegionUnion[OpenInterval[0, 5], OpenInterval[5, 8]], {x}] // FullSimplify
    
    gives:
    x \[Element] Reals && (0 < x < 5 || 5 < x < 8)
    
  • closed intervals:
    RegionMember[RegionUnion[ClosedInterval[0, 5], ClosedInterval[5, 8]], {x}] // FullSimplify
    
    gives:
    0 <= x <= 8
    
$\endgroup$
2
  • $\begingroup$ +1. That approach works in higher dimensions. $\endgroup$
    – user64494
    Apr 28, 2020 at 18:43
  • $\begingroup$ And also works for Integers instead of Reals. $\endgroup$ Jan 12 at 20:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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