pythonpython-2.7sympyevalf

How can I substitute the value of one variable in a multivariate function?


Suppose, I have a function f(x,y)=x2+y2. Now, I would like to substitute x=2, keeping y symbolic. I tried with

f.evalf(subs={x:2})

But it is not substituting the value of x, and just giving me the original expression.


Solution

  • You didn't resolve all the symbols, so you won't get an evaluation which is what evalf tries to do - it only works if it substitutes all the variables in your expression.

    You can however use subs directly on your expression.

    >>> from sympy import *
    
    >>> x, y = symbols('x y')
    
    >>> expr = x**2 + y**2
    
    >>> expr.subs(x, 2)
    y**2 + 4
    

    And if needed, could subsequently call evalf().