Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a list of the symbols in a sympy expression?

For example, if I run

import sympy x, y, z = sympy.symbols('x:z') f = sympy.exp(x + y) - sympy.sqrt(z) 

is there any method of f that I can use to get a list or tuple of sympy.Symbol objects that the expression contains? I'd rather not have to parse srepr(f) or parse downward through f.args.

In this case, g.args[0].args[1].args[0] gives me Symbol("z"), while g.args[1].args[0].args gives me the tuple (Symbol("x"), Symbol("y")), but obviously these are expression-specific.

like image 331
Michael A Avatar asked May 03 '15 20:05

Michael A


People also ask

How do you evaluate expressions 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 .

Which library of Python is used for symbolic computations?

What is SymPy? SymPy is a Python library that allows you to compute mathematical objects symbolically.

How do you approximate in SymPy?

Basics. Exact SymPy expressions can be converted to floating-point approximations (decimal numbers) using either the . evalf() method or the N() function.

How can I substitute 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.


1 Answers

You can use:

f.free_symbols 

which will return a set of all free symbols.

Example:

>>> import sympy >>> x, y, z = sympy.symbols('x:z') >>> f = sympy.exp(x + y) - sympy.sqrt(z) >>> f.free_symbols set([x, z, y]) 
like image 66
JuniorCompressor Avatar answered Sep 18 '22 18:09

JuniorCompressor