Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sympy "global" substitution

I have a number of symbolic expressions in sympy, and I may come to realize that one of the coefficients is zero. I would think, perhaps because I am used to mathematica, that the following makes sense:

from sympy import Symbol
x = Symbol('x')
y = Symbol('y')
f = x + y
x = 0
f

Surprisingly, what is returned is x + y. Is there any way, aside from explicitly calling "subs" on every equation, for f to return just y?

like image 462
mboratko Avatar asked Mar 05 '12 00:03

mboratko


1 Answers

I think subs is the only way to do this. It looks like a sympy expression is something unto itself. It does not reference the pieces that made it up. That is f only has the expression x+y, but doesn't know it has any link back to the python objects x and y. Consider the code below:

from sympy import Symbol
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')

f1 = x + y
f2 = z + f1
f1 = f1.subs(x,0)
print(f1)
print(f2)

The output from this is

y
x + y + z

So even though f1 has changed f2 hasn't. To my knowledge subs is the only way to get done what you want.

like image 96
Brad Campbell Avatar answered Sep 23 '22 01:09

Brad Campbell