taschini / pyinterval

PyInterval — Interval arithmetic in Python
http://pyinterval.readthedocs.io
Other
83 stars 25 forks source link

Difference between two intervals #9

Open jsgounot opened 7 years ago

jsgounot commented 7 years ago

Hi,

I don't know if it's already existent, but I would like to calculate the difference between two intervals, like that :

i1 = interval([3,4], [7,9]) i2 = interval([0,10])

foo(i1, i2) -> interval([0,2], [5,6], [10,10])

Is there a function doing that right now ?

taschini commented 7 years ago

I think you might be referring to set difference, also known as relative complement. In that case, we must not forget that we are dealing with intervals over the (extended) real line, so, in fact,

[0, 10] ∖ ([3,4] ∪ [7,9]) = [0, 3) ∪ (4, 7) ∪ (9, 10]

which is different from the value you expect, [0,2] ∪ [5,6] ∪ [10,10].

PyInterval cannot implement set difference, as the set difference between two closed sets is not necessarily closed (and this library only handles closed intervals), but it could implement an approximation of it by taking the closure of the set difference:

closed_difference([0, 10], [3,4] ∪ [7,9]) := [0, 3] ∪ [4, 7] ∪ [9, 10]

Be warned, though, that this approximation breaks a fundamental property of set difference: AB = CBC = ∅, but in the case of this approximation ([3,4] ∪ [7,9]) ∩ ([0, 3] ∪ [4, 7] ∪ [9, 10]) = [3, 3] ∪ [4, 4] ∪ [7, 7] ∪ [9, 9].

I haven't had yet a use case for implementing closed_difference, but if you can provide me with one, I can easily add it.

brunompacheco commented 4 years ago

In my current application I am interested in the length of the difference of two intervals, more precisely in knowing whether the difference is empty or not, so the closed difference would be quite useful.

adishavit commented 2 years ago

My use case is the same - I'm interested in the remaining sub-interval lengths after clipping, poking or subtracting (using such closed_difference). For this open v.s closed is unimportant. I would love to see an implementation for this.

Leden commented 2 years ago

Hello, I'd also make use of closed_difference. My use-case is to determine free slots in appointments schedule available for booking. I'd cast datetimes into unixtime (float), diff the working hours interval against already booked appointments, then cast unixtime intervals back to datetimes.