I declare a variable, define an expression using the variable
from sympy import *
x = symbols ('x')
f = 2 * x
and then assign a value to the variable
x = 42
How can I substitute the variable in the expression by its current value? For obvious reasons
f.subs (x, x)
does not work. I know that I can use a different variable
xx = 42
f.subs (x, xx)
but ...
Nobody likes to get compared to their new girlfriend's ex, but in Matlab you could simply write subs (f)
which would be the equivalent to SymPy's f.subs ()
without any parameters, to substitute all intermediately assigned variables.
f.subs ('x', x)
. Note that if you writex = symbols('x')
, and thenx = ....
, you remove your direct access to the symbol. Matlab is a dedicated environment; each tool has its strong and weak points. Feel free to choose the one that best fits your workflow. By the way, a function that loops through an expression, looks up the variable names into the globals and does substitutions, wouldn't be that hard to write. – Hailstormf.subs ('x', x)
makes my life a bit easier. In aaguirre's GlobalSubs I still have to list all the variables I want to substitute. I am still dreaming of an automaticf.subs()
that substitutes all currently assigned variables. But as you said, as soon as I understand a bit more about sympy, I will try to write that function ... – Porush