Assigning a variable directly does not modify expressions that used the variable retroactively.
>>> from sympy import Symbol >>> x = Symbol('x') >>> y = Symbol('y') >>> f = x + y >>> x = 0 >>> f x + y
The subs() function in SymPy replaces all occurrences of first parameter with second. This function is useful if we want to evaluate a certain expression. For example, we want to calculate values of following expression by substituting a with 5.
subs() method, we can substitute all instances of a variable or expression in a mathematical expression with some other variable or expression or value. Parameters: variable – It is the variable or expression which will be substituted. substitute – It is the variable or expression or value which comes as substitute.
To evaluate a numerical expression into a floating point number, use evalf . SymPy can evaluate floating point expressions to arbitrary precision. By default, 15 digits of precision are used, but you can pass any number as the argument to evalf .
To substitute several values:
>>> from sympy import Symbol >>> x, y = Symbol('x y') >>> f = x + y >>> f.subs({x:10, y: 20}) >>> f 30
The command x = Symbol('x')
stores Sympy's Symbol('x')
into Python's variable x
. The Sympy expression f
that you create afterwards does contain Symbol('x')
, not the Python variable x
.
When you reassign x = 0
, the Python variable x
is set to zero, and is no longer related to Symbol('x')
. This has no effect on the Sympy expression, which still contains Symbol('x')
.
This is best explained in this page of the Sympy documentation: http://docs.sympy.org/latest/gotchas.html#variables
What you want to do is f.subs(x,0)
, as said in other answers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With