pythonfunctionsympyresultsetevaluate

How do I evaluate a Sympy function in Python?


I am facing a major issues in python using sympy. I didn't find any solutions to my problem or at least, I couldn't apply the solutions I found on my problem.

import sympy as sp
import math as ma 
import numpy as np

E1=72500
A1=15

U01,s,C1,U02 = sp.symbols("U01,s,C1,U02")

u1 = sp.symbols("u1", cls=sp.Function)
eqs=sp.Eq(E1*A1*u1(s).diff(s)+180+U02,0)
sol=sp.dsolve(eqs,dict=True)
expr=sol.args[1]
u1=sp.lambdify(s,expr.subs(C1,U01))

print(u1(s))
#gives me :  U01 - 9.19540229885057e-7*U02*s - 0.00016551724137931*s

expression1=u1(10)-54
expression2=u1(7)-99

eq1=sp.Eq(expression1,0)
eq2=sp.Eq(expression2,0)

solution = sp.solve([eq1,eq2],[U01,U02])
U01=float(solution[U01])
U02=float(solution[U02])

print(u1(55))
# gives me : U01 - 5.05747126436782e-5*U02 - 0.00910344827586207

I want to evaluate u1(55), but I still get the expression.

Thank you very much in advance.

I expect to get :

-621.0000000000018


Solution

  • Don't override U01 and U02 by numerical values, use intermediate variables. You have to evaluate your lambda function with solution previously found:

    ...
    solution = sp.solve([eq1, eq2], [U01, U02])
    U01_val = float(solution[U01])
    U02_val = float(solution[U02])
    
    result = u1(55).evalf(subs={U01: U01_val, U02: U02_val})
    print(result)
    
    # Output
    -621.000000000001
    

    Or simply:

    ...
    solution = sp.solve([eq1, eq2], [U01, U02])
    
    result = u1(55).evalf(subs=solution)
    print(result)
    
    # Output
    -621.000000000001