 # Substituting Symbols for other Symbols

I am working on a project for school using sympy as a Computer Algebra System. I have created several symbolic variables and a few expressions involving them just fine using the following code:

x = sym.Symbol(‘x’)
y = sym.Symbol(‘y’)
a = sym.Symbol(‘a’)
b = sym.Symbol(‘b’)
f = a - x - (4xy)/(1+x2)
g = b*x * (1 - y/(1+x
2))
f_x = sym.diff(f, x)
f_y = sym.diff(f, y)
g_x = sym.diff(g, x)
g_y = sym.diff(g, y)

However, now I need to evaluate f_x, f_y, g_x, and g_y using the substitutions x = a/5, y = (a**2 +5)/5 and tried using the following:

f_x.evalf(subs={x:a/5, y:(a**2 +5)/5})

However, this simply returns my original f_x with no substitutions! I am not sure what I am doing wrong…

How did you measure/observe that you got the original `f_x` back?
My guess is you wrote other things as well, but didn’t include those other things. If you write your code to file you have a way to reproduce it and won’t get any interference from things you’ve forgotten about since you would re-run the program completely after each modification.

(also, take care to ensure that code you share is intact, if you try to reproduce what you describe using your post you’ll find it can’t be copied and run)

``````import sympy as sym

x = sym.Symbol('x')
y = sym.Symbol('y')
a = sym.Symbol('a')
b = sym.Symbol('b')
f = a - x - (4 * x * y) / (1 + x**2)
g = b * x * (1 - y / (1 + x**2))
f_x = sym.diff(f, x)
f_y = sym.diff(f, y)
g_x = sym.diff(g, x)
g_y = sym.diff(g, y)

print('original f_x:', f_x)
print('after subs:  ', f_x.evalf(subs={x: a / 5, y: (a**2 + 5) / 5}))
``````
``````original f_x: 8*x**2*y/(x**2 + 1)**2 - 4*y/(x**2 + 1) - 1
after subs:   8.0*x**2*y/(x**2 + 1.0)**2 - 4.0*y/(x**2 + 1.0) - 1.0
``````

… oh the only difference is floats

well then, in that case, did sympy promise to do something other than this for that operation?

``````>>> help(x.evalf)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False) method of sympy.core.
symbol.Symbol instance
Evaluate the given formula to an accuracy of n digits.
Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g.
subs={x:3, y:1+pi}. The substitutions must be given as a
dictionary.
``````

Does what you supplied for subs match that description? Have you provided enough information for evalf to be able to do its thing?

``````>>> f_x.subs({x: a / 5, y: (a**2 + 5) / 5})
8*a**2*(a**2/5 + 1)/(25*(a**2/25 + 1)**2) - 1 - 4*(a**2/5 + 1)/(a**2/25 + 1)
``````