Question

Let's say that I know that x is bigger than y and both x and y are bigger than 0.

Can someone please help me write a function that takes two linear formulas (+/- only) and returns which one is bigger?

For example:

foo("x+y","2*x") #should return 2
foo("2*x","x+y") #should return 1
foo("x","2*y") #should return 0 (can't decide)

thanks alot!

Was it helpful?

Solution

The best way to do this in SymPy is to use the assumptions system.

First off, don't try to do tokenizing. Just use sympify if you have to input as strings, and if you don't have to, just create the expressions using symbols, like

x, y = symbols('x y')
a = x - y
b = 2*x

Please read the SymPy tutorial for more information.

The assumptions system doesn't support inequalities directly yet, so to represent x > y, you need to state that x - y is positive. To ask if 2*x > x - y, i.e., if 2*x - (x - y) is positive, given that x, y, and x - y are positive, do

In [27]: ask(Q.positive((2*x) - (x - y)), Q.positive(x) & Q.positive(y) & Q.positive(x - y))
Out[27]: True

The first argument to ask is what you are asking and the second argument is what you are assuming. & is logical and, so Q.positive(x) & Q.positive(y) & Q.positive(x - y) means to assume all three of those things.

It will return False if it knows it is false, and None if it can't determine. Note that SymPy works in a complex domain, so not positive doesn't necessarily mean negative. Hence, you should probably call ask on the negated expression as well if you get None, or call it again with negative instead of positive. If you want to include 0 (i.e., use >= instead of >, use nonnegative instead of positive and nonpositive instead of negative.

It isn't as smart as it could be yet, so you'll get a lot of Nones now when the answer could be known. In particular, I don't think it will really use the x > y fact very well at this point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top