Clark R.
Clark R.

Reputation: 23

Trouble making a SymPy Solved Equation Solution into a Function

I'm trying to use Python (3) to process the results of a thermodynamics lab. Part of that involves finding a best fit curve, and to guess the exponent I need I'm using SymPy to solve for it, then finding the average after running my data through it (It should be a constant).

Only I'm stuck. SymPy solves the equation just fine, but getting the solution into a usable form is stumping me. Is there any way to get it back from SymPy as something other than symbolic? This is what I've tried so far:

def Solve_Tao(Td,TC,t):
"""Solves for Decay Constant and Returns Average For Data"""
T = t   # Time, Storing so it doesn't become symbolic
Tao, t, Tinf, Tsi, Ts_t = sp.symbols('Tao t Tinf Tsi Ts_t')
sp.init_printing(use_unicode=False)
TaoStrings = sp.solve([(Tinf + (Tsi - Tinf) * sp.exp(-t/Tao))-Ts_t], [Tao])
TaoStrings = sp.sstrrepr(TaoStrings)
TaoS = TaoStrings[6:9] + 'np.'+ TaoStrings[9:-1]
eq = parse( TaoS )

Tinf = Td
Ts_t = TC
Tsi = TC[0]
t  = T
tao = eq
print('tao',tao)
return tao

But printed tao value turns out to be 0 (which it should not). Type(eq) gives tao '<_ast.Module object at 0x10773b3c8>'. Is there something I can do with this? If not, is there a way I can use the solved equation out of SymPy?

Your help is appreciated.

Upvotes: 2

Views: 373

Answers (1)

Bill Bell
Bill Bell

Reputation: 21663

It might be easier to evaluate the solution as it is. For instance, to evaluate the solution at t=0 use the subs method.

>>> soln = sp.solve([(Tinf + (Tsi - Tinf) * sp.exp(-t/Tao))-Ts_t], [Tao])[Tao]
>>> soln
-t/log((Tinf - Ts_t)/(Tinf - Tsi))
>>> soln.subs(t,0)
0

If you need to evaluate the solution for all four variables simply repeat sub.

soln.subs(t,0).subs(Tinf,<something>).subs(Ts_t,<something>).subs(Tsi,<something>)

If you happen to have all four variable values in a dictionary d then you can use this form:

soln.subs(d)

Upvotes: 2

Related Questions