I have several expressions I read from a file and they all have one variable in common. I want to go through each equation and write this variable in terms of the other variables and a new constant. For example, my equations look like this:
x1**(-1.0)*x2
x1**(-1.0)*y1
x1**(-1.0)*y2
and I want to do this:
x1 = x2/a1
x1 = y1/a2
x1 = y2/a3
The way I tried to do this, (for example for the first one) is this:
from sympy import *
from sympy.parsing.sympy_parser import parse_expr
eq1 = "x1**(-1.0)*x2" # I normally read this from a file
a1 = symbols('a1')
eq1 = parse_expr(eq1)
variable1 = list(eq1.free_symbols)[0]
print(variable1)
eq1 = solve(eq1-a1,variable1)
eq1 = eq1[0]
print(eq1)
And this is the output I get, by running this exactly same code 5 times in a row:
x1
x2/a1
x2
a1*x1
x2
a1*x1
x1
x2/a1
x2
a1*x1
So the problem is that when I try to pick the first variable in my expression variable1 = list(eq1.free_symbols)[0]
the first variable is not always the same (sometimes it is x1, sometimes it is x2), even if the expression I use is the same all the time. It seems to be just random, which I really hope it's not. Can someone help me figure out how to always pick the variable I need. So for the 3 expression I wrote in the beginning, I want to always pick the x1 when calling variable1 = list(eq1.free_symbols)[0]
(or an equivalent function). Thank you!
If your variable1
is always x1
, you should be able to just make a symbol x1
and use it.
variable1 = sympy.symbol('x1')
`
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.