Using SymPy for General Analysis and Solving Equations

I want to be able to parse string equations (equal to 0) and then solve them using a dictionary of variables that I have access to.

For instance:

s = '(x/z)-y' eq = parse(s) eq.solve({'x': 10, 'y': 5}) print(eq) >>> {'z': 2} 

Now I wrote code that did something like this a month ago, but I just can't find it. I remember, however, that I used SymPy and its sympify function, as well as a solution function. I checked the documentation for these functions, but I was not able to look up, how to make them work the way I want.

And another question: Is it possible to wrap variables in some way so that I can use something more than just a letter for them? Example: instead of "x" I could have "{myvar-42}"

EDIT:

Well, finally, I was able to write code that did what I wanted:

 eq = sympify('(x/y)-z', locals={'x': 10, 'z': 5}) solution = solve(eq, dict=True) print(solution) >>> [{'z': 2}] 

But my "extra" question remains.

+6
source share
1 answer

As you find, sympify converts strings to SymPy expressions.

To answer another question, character names can be anything, but sympify will only parse valid Python identifiers for character names. But you can do

 >>> Symbol('{myvar-42}') + 1 {myvar-42} + 1 

And note that valid Python identifiers should not be single letters. They can be any combination of letters, numbers, and underscores that do not start with a number, such as x_2 or abc123 .

If you still need to parse strings but want invalid Python identifiers to be character names, perhaps the purest way would be to use regular names and substitute them for others, for example

 >>> expr = sympify('x + 1') >>> expr.subs(Symbol('x'), Symbol('{myvar-42}') {myvar-42} + 1 

Finally, to replace characters with letters, you can use the locals argument for sympify as you did, or if you want to replace them later, use subs:

 >>> x, y, z = symbols('xy z') >>> expr = sympify('x/z - y') >>> expr.subs({x: 10, y: 5}) 10/z - 5 
+5
source

All Articles