SymPy: How to get values from expression
-
27-10-2019 - |
Question
I am trying to write a simple SymPy function.
a = Wild('a')
b = Wild('b')
p = Wild('p')
q = Wild('q')
...
if (U).match(b/(a+s)):
return b*exp(-a*t)
Lets say that U = 3/(7+s)
. I would like my result to be 3*exp(-7*t)
, but it just returns b*exp(-a*t)
.
Is there a way to get those values and assign them to a and b?
Solution
Sure. First, set up the system:
>>> from sympy import var, Wild, exp
>>> s = var("s")
>>> t = var("t")
>>> a = Wild("a")
>>> b = Wild("b")
>>> U = 3/(7+s)
The .match
method returns a dictionary:
>>> U.match(b/(a+s))
{b_: 3, a_: 7}
>>> m = U.match(b/(a+s))
which can then be passed as an argument to .subs
:
>>> target = b*exp(-a*t)
>>> target
b_*exp(-t*a_)
>>> target.subs(m)
3*exp(-7*t)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow