Home > Net >  taking intersection over a continous range of values in python
taking intersection over a continous range of values in python

Time:03-25

I have a domain of values on which I want to take intersection. for example. 0 <= n1 < 2*pi and -pi <= n2 < pi now the n1 intersection n2 would be [0,pi). The ranges of n1 and n2 can be anything. I want to know if there is an easy way to do this. I am currently using nested if-else to do this. I also want to know if their intersection is null if there is no overlap.

CodePudding user response:

this is a variant:

from dataclasses import dataclass


@dataclass(frozen=True)
class Range:
    frm: float
    to: float
    # assert frm <= to


def intersect(ranges):
    if ranges[0].to < ranges[1].frm or ranges[1].to < ranges[0].frm:
        # no overlap
        return None

    return Range(frm=max(ranges[0].frm, ranges[1].frm),
                 to=min(ranges[0].to, ranges[1].to))

print(intersect((Range(frm=0, to=2), Range(frm=-1, to=1))))
# -> Range(frm=0, to=1)

i used a dataclass in order to make it a bit more clear what is going on here. note that for the Range i assume the invariant frm <= to.

you can get rid of your nested if using max and min.

CodePudding user response:

In module sympy there is a class Set and several subclasses, including Interval.

from sympy import Interval, Intersection, pi

n1 = Interval.Ropen(0, 2*pi)
n2 = Interval.Ropen(-pi, pi)

n3 = Intersection(n1, n2)

print(n3)
# Interval.Ropen(0, pi)

Relevant documentation: sympy Sets

  • Related