Search code examples
sympyinequalityabsolute-value

Using sympy to solve a two-sided inequality with absolute value


Relatively simple math problem, find the range over which 3 <= Abs[6 - x] <= 5. Not hard to solve by hand, and Mathematica nails it, with the answer 1 <= x <= 3 || 9 <= x <= 11.

The closest I can get with sympy is

from sympy import *
x = symbols('x', real=True)
reduce_inequalities([3 <= abs(6 - x), abs(6 - x) <= 5], x)

This results in

1≤𝑥∧𝑥≤11∧(9≤𝑥∨𝑥≤3)

which, if I read it correctly, is sympy's way of saying

1 <= x || x< 11 || (9 <= x || x <= 3)

which is both odd and wrong. What am I missing here?


Solution

  • This is the output from SymPy:

    In [1]: from sympy import *
       ...: x = symbols('x', real=True)
       ...: reduce_inequalities([3 <= abs(6 - x), abs(6 - x) <= 5], x)
    Out[1]: 1 ≤ x ∧ x ≤ 11 ∧ (9 ≤ x ∨ x ≤ 3)
    

    What this means is that 1 <= x <= 11 AND (x >= 9 OR x <= 3).

    This is logically equivalent to the Mathematica output that you refer to although perhaps not expressed as clearly. You can manipulate the output to the same form with:

    In [2]: r = reduce_inequalities([3 <= abs(6 - x), abs(6 - x) <= 5], x)
    
    In [3]: r.as_set()
    Out[3]: [1, 3] ∪ [9, 11]
    
    In [4]: r.as_set().as_relational(x)
    Out[4]: (1 ≤ x ∧ x ≤ 3) ∨ (9 ≤ x ∧ x ≤ 11)