Reputation: 227
How do I replace a variable in a function with a new definition of the initial variable ?
import sympy as sy
g, a, x = sy.symbols("g a x")
g = 5*a*x
Entering g in the interpreter at this point prints:
5*a*x.
Now I would like to replace the printed a with an alpha. Why does the following not work?
a = sy.symbols("alpha")
g = g.subs(a,a)
I am well aware that i could use the following:
import sympy as sy
g, a, x = sy.symbols("g a x")
g = 5*a*x
alpha = sy.symbols("alpha")
g = g.subs(a,alpha)
But I would like to understand why the former approach is not working. Generally I am interested how the assigned name a= and the string in symbols("a") are connected. Must they be the same for sympy to work correctly ?
Upvotes: 1
Views: 275
Reputation:
g = g.subs(a, a)
can never do anything, as it's replacing a thing with itself.
To replace a
with something else
g.subs(a, sy.symbols('alpha'))
should be used. The relevant topic in SymPy docs is Assignment does not create a relation. A simpler example:
a = sy.symbols('a')
b = a + 3 # b is now a+3
a = 5 # b is still a+3 and it will not become 8
At the end of this code, the Python variable a
has no relation to the SymPy symbol named "a". The variable is 5; the symbol is still Symbol("a")
and will forever be, as SymPy expressions are immutable. Instead of a = 5
one should have done b.subs(a, 5)
to perform the substitution.
I am interested how the assigned name a= and the string in symbols("a") are connected.
They are not connected at all. It's convenient to use Python variable a
to point to a symbol named "a", that is the only reason people do that. Unfortunately the pattern then misleads them into thinking that if they put a
= something new, that will have an effect on Symbol("a")
-- it will not. The only effect is that Python variable now points to something else; the expressions containing Symbol("a")
are unaffected.
Upvotes: 1