Search code examples
pythonboolean-operations

Is there standard Python class to do boolean operations on float ranges?


I need to collect multiple pieces of information about approximate value of a float variable. The information looks like "39 < x < 41" or just "x < 14.4". Also, the variable has its ultimate min and max values.

I would want to have a class that contains such information in form of float intervals. I would also like to perform Boolean operations on such intervals so that it would look like:

float_interval(1,5) and float_interval(2,6) == float_interval(2,5)
float_interval(1,2) and float_interval(3,4) == None
float_interval(1,2) or float_interval(3,4) == i_do_not_know_yet

Am I describing some well-known class or I am to write it myself?

If anyone interested the variable is a fetus gestational age in weeks during pregnancy. In many case-control studies fetal age is not always mentioned directly, but instead there is an information on pregnancy trimester or whehter delivery was term or preterm and so on. Hence, I can infer approximate gestational age and put it to the corresponding category.


Solution

  • The very capable sympy package has an Interval class builtin. Example code:

    import sympy
    I1 = sympy.Interval(1, 5)
    I2 = sympy.Interval(2, 6)
    I3 = I1 & I2
    print(I3)
    

    See the sympy interval documentation for details.