Patrik Lechner
Patrik Lechner

Reputation: 41

Sympy: solve for fraction

I have an equation and I need to solve it for a fraction. I have more complex fomulas to solve but here is a minimal example: take the following simple function Y = X*a. I want to solve for Y/X, so I expect Y/X =a. Here is the code, it produces an empty set of answers

from sympy import *
X,Y,a = symbols('X Y a')
testEq = Eq(Y,X*a)
solve(testEq,Y/X)

I guess I'm misunderstanding something, any help appreciated!

Upvotes: 1

Views: 1012

Answers (2)

smichr
smichr

Reputation: 19047

In this issue, a focus routine handles such a request once an auxiliary expression is added to the one of interest:

>>> eq = Eq(y, x*a)
>>> aux = Eq(b, y/x)
>>> focus((aux, eq), b)
{b: a}

Such a routine does not eliminate the need for human intervention, it just assists by allowing the user to state the relationship of interest and add that to the current equation(s) from which the implications are then deduced/solved.

Upvotes: 0

user6764549
user6764549

Reputation:

The solve function can solve for sub-expressions provided they appear "as is" in the equation being solved. For example, in the following code, solve returns an empty solution for testEq but it returns the correct solution for testEq2 which is the same equation rearranged in terms of Y/X.

from sympy import *
X,Y,a = symbols('X Y a')
testEq = Eq(Y,X*a)
solve(testEq,Y/X)
testEq2 = Eq( Y/X, a )
sol = solve(testEq2,Y/X)

This is not weird or unreasonable at all. If you look at the source code of the solve function it uses code like

>>> testEq.has( Y/X ) # returns False
>>> testEq2.has( Y/X ) # returns True

to check if the symbol ( or sympy object ) that we are solving is present in the equation. If SymPy had to check for all possible ways in which the symbols of an expression can be combined into sub-expressions, the code would become extremely complicated for something which can be easily achieved in other ways ( like solving for Y and dividing by X, in this example ).

Packages for symbolic computations are there to help us handle complicated mathematical equations. But they are not a substitute for human intelligence. More often than not, we need to guide these packages to help them give the answer in a form we want while working around their limitations.

Upvotes: 3

Related Questions