0

Using sympy solve() or reduce_inequalities() works fine for non compound inequalities like 2 - 6 * x <= -4 but it cannot do compound ones.

Is there a different sympy function or a different import that can solve a compound inequality? I can't seem to find anything in the sympy docs or on Google.

Stef
  • 13,242
  • 2
  • 17
  • 28
  • 2
    Are you looking for [this](https://groups.google.com/g/sympy/c/GTqyawl-f7w)? Compound inequalites such as `a < x < b` can be split into `a < x and x < b`. – B Remmelzwaal Jan 29 '23 at 18:03
  • 2
    `sympy` can override the definition of `<` to produce new symbolic expressions instead of a Boolean value, but `a < b < c` is fundamentally the same as `a < b and b < c`, no matter what types the operands have. (This is implemented at the parser level.) Since you can likewise not override what `and` means, I don't think you can accomplish what you want without writing `4 < x - 8 < 10` in a different manner, such as `(4 < x - 8) & (x - 8 < 10)` (note the the parentheses are necessary, due to `&` having higher precedence than the other operators). – chepner Jan 29 '23 at 18:04
  • You guys are right! Currently I'm just breaking the equation down into 2 parts and just removing the "oo" to get the answer. – Kevin Schnaubelt Jan 29 '23 at 18:24
  • 2
    I tried `reduce_inequalities((4 < x-8, x-8 < 10))` and the result was printed as `(12 < x) & (x < 18)`. Note that the double parentheses are important. – Stef Jan 29 '23 at 18:26

2 Answers2

1

solveset() function can solve both simple and compound inequalities.

For example, to solve the compound inequality (2 - 6x <= -4) AND (3x + 1 > 4), you can use the following code:

from sympy import *
x = Symbol('x')

ineq1 = Eq(2 - 6*x, -4)
ineq2 = Eq(3*x + 1, 4)

solveset(And(ineq1, ineq2), x)

you can use linsolve() function to solve system of linear equations and inequalities.

linsolve([2 - 6*x - 4, 3*x + 1 - 4], x)
vineet singh
  • 173
  • 2
  • 12
  • which version of sympy are you using? When executing the solveset command I'm getting `ValueError: Eq(2 - 6*x, -4) & Eq(3*x + 1, 4) is not a valid SymPy expression` with 1.11.1 – Davide_sd Jan 30 '23 at 08:44
0

As others have mentioned...

4 < x - 8 < 10

is the same as...

4 < x - 8 AND x - 8 < 10

So I'm simply doing...

solve(4 < x - 8)
solve(x - 8 < 10)

and just combining the results. So...

(12 < x) & (x < 18) or (12,18) or 12 < x < 18

*EDIT User Stef also pointed out that you can give reduce_inequalities() these two equations as two arguments!

reduce_inequalities((4 < x-8, x-8 < 10))