Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using sympy to solve an inequality with two variables

I’m trying to use Sympy to solve 0 < x + y <= 4 in the case where both x and y are positive integers or 0, in the hopes to have it return a list of tuples that solves the inequality.

import sympy as sp

# Assign variables
x, y = sp.symbols('x y', natural0 = True)

# Define the inequalities
ineq1 = sp.And(0 < x + y, x + y <= 4)
ineq2 = x >= 0
ineq3 = y >= 0

# Solve the inequality
result = sp.solve([ineq1, ineq2, ineq3], [x,y])

Expected result:
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (4, 0)]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Solve() can not do that. You can just do it manually:

import sympy as sp

x, y = sp.symbols('x y')

ineq1 = sp.And(0 < x + y, x + y <= 4)
ineq2 = x >= 0
ineq3 = y >= 0

result = []
for xi in range(5):
    for yi in range(5):
        A = ineq1.subs({x: xi, y: yi})
        B = ineq2.subs({x: xi, y: yi})
        C = ineq3.subs({x: xi, y: yi})
        if A and B and C:
            result.append((xi, yi))

print(result)

Prints

[(0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (4, 0)]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading