Reputation: 688
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, i.e., everything that is not a Symbol
?
Upvotes: 1
Views: 1303
Reputation: 4405
The method atoms
returns a set of all atomic (i.e., 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 A.S. 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)
Upvotes: 2