Is it possible to equate the Output of solving Single Variable Linear Inequality with Python's numpy ranges?
Question:
I’ve been browsing everywhere to find the answer but nothing. So I tried it myself with code like below but still failed.
import numpy as np
from sympy import *
x = symbols("x", real=True)
init_printing(use_unicode=True)
ekpr = (3*x - 2 < 2*x + 1)
sol = [solve(ekpr, x) for x in np.arange(0, 5, 1)]
sol
the output is like this:
3⋅x - 2 < 2⋅x + 1
[ <3, <3, <3, <3, <3]
The output I want is: 0, 1 and 2 as this corresponds to x < 3.
Or other than numpy range, get it in some other way?
Any help will be highly appreciated.
Answers:
I think it may help to use the lambdify function for sympy expressions (https://docs.sympy.org/latest/modules/utilities/lambdify.html). With that, I could get to a kind of workaround, although it’s not really clean because you must make assumptions about the set of numbers for which the condition is fulfilled (for example, I restrict the search to the range [0, 100]):
from sympy import *
x = symbols("x", real=True)
expression = x<3
expr_lambda = lambdify(x, expression)
list = []
for i in range(100):
if expr_lambda(i):
list.append(i)
print (list)
From this, I get the output
[0, 1, 2]
Instead of trying to carefully re-use x
, substitute the values from your array and see if the result is True
>>> x = symbols("x")
>>> ekpr = (3*x - 2 < 2*x + 1)
>>> [n for n in np.arange(5) if ekpr.subs({x: n})]
[0, 1, 2]
>>> (3*x - 2 < 2*x + 1).as_set() & Range(5) # use set ops for univariate expression
{0, 1, 2}
I’ve been browsing everywhere to find the answer but nothing. So I tried it myself with code like below but still failed.
import numpy as np
from sympy import *
x = symbols("x", real=True)
init_printing(use_unicode=True)
ekpr = (3*x - 2 < 2*x + 1)
sol = [solve(ekpr, x) for x in np.arange(0, 5, 1)]
sol
the output is like this:
3⋅x - 2 < 2⋅x + 1
[ <3, <3, <3, <3, <3]
The output I want is: 0, 1 and 2 as this corresponds to x < 3.
Or other than numpy range, get it in some other way?
Any help will be highly appreciated.
I think it may help to use the lambdify function for sympy expressions (https://docs.sympy.org/latest/modules/utilities/lambdify.html). With that, I could get to a kind of workaround, although it’s not really clean because you must make assumptions about the set of numbers for which the condition is fulfilled (for example, I restrict the search to the range [0, 100]):
from sympy import *
x = symbols("x", real=True)
expression = x<3
expr_lambda = lambdify(x, expression)
list = []
for i in range(100):
if expr_lambda(i):
list.append(i)
print (list)
From this, I get the output
[0, 1, 2]
Instead of trying to carefully re-use x
, substitute the values from your array and see if the result is True
>>> x = symbols("x")
>>> ekpr = (3*x - 2 < 2*x + 1)
>>> [n for n in np.arange(5) if ekpr.subs({x: n})]
[0, 1, 2]
>>> (3*x - 2 < 2*x + 1).as_set() & Range(5) # use set ops for univariate expression
{0, 1, 2}