简体   繁体   中英

Extracting the numbers out of a SymPy expression

How can I extract all the numerical values from a SymPy expression? For example, for this expression: sin(a/pi + a) + 0.629116159212 , I want pi , -1 , and 0.629116159212 .

I found the srepr function in SymPy, which returns for the example:

Add(sin(Add(Mul(Pow(pi, Integer(-1)), Symbol('a')), Symbol('a'))), Float('0.62911615921200004', precision=53))

How can I extract all the numbers from this, ie, everything that is not a Symbol ?

  • The method atoms returns a set of all atomic (ie, unsplittable) components of an expression.

  • The attribute is_number tells you whether some expression (or atom) is a number.

Combined:

from sympy import sin, pi
from sympy.abc import a

expr = sin(a/pi + a) + 0.629116159212
numbers = {atom for atom in expr.atoms() if atom.is_number}

Now, if you need to preserve the count of appearances, things get a bit more complicated, since atoms returns a set. Here, we additionally can use:

  • Alternative 1: sympy.preorder_traversal (or postorder_traversal ) which iterates through all subexpressions of an expression. (Thanks to Oscar Benjamin and AS Meurer .)

  • Alternative2: The method find of expressions, which returns all expressions matching some criterion.

  • The attribute is_Atom .

from sympy import sin, pi, preorder_traversal
from sympy.abc import a

expr = sin(a/pi + 1/a) + 0.629116159212

is_atomic_number = lambda expr: expr.is_Atom and expr.is_number

# Alternative 1:
[
    subexpression
    for subexpression in preorder_traversal(expr)
    if is_atomic_number(subexpression)
]

# Alternative 2:
expr.find(is_atomic_number,group=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM