Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substitute multiple symbols in an expression in sympy?

Tags:

python

sympy

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 
like image 634
Wesley Avatar asked Oct 04 '15 05:10

Wesley


People also ask

How do you substitute values in SymPy?

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.

How do you substitute a value in an expression in Python?

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.

How do you evaluate an expression in SymPy?

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 .


2 Answers

To substitute several values:

>>> from sympy import Symbol >>> x, y = Symbol('x y') >>> f = x + y >>> f.subs({x:10, y: 20}) >>> f 30 
like image 189
Wesley Avatar answered Sep 22 '22 10:09

Wesley


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.

like image 29
Adrien Avatar answered Sep 18 '22 10:09

Adrien