Reputation: 350
I need to integrate a system of equation, and the main problem I faced is that I can't convert equations of one variable (in the symbolic expression, its one symbol) to functions.
This is the minimal working example:
rr = sy.Symbol('r')
exps = 4*rr+5
def f(rr):
return exps
f(5)
gives 4*rr+5
Upvotes: 0
Views: 2208
Reputation: 80279
The parameter 'rr' is a different variable than the global variable 'rr'. f(5)
returns an expression with the global variable 'rr' and doesn't use the parameter.
To achieve what you're trying to do, substitute the global parameter with the value of the local parameter:
import sympy as sy
rr = sy.Symbol('r')
exps = 4*rr+5
def f(param_rr):
return exps.subs({rr: param_rr}).simplify()
print(f(5))
If you need to call the function a lot, and don't use symbolic expressions as parameter, there is lambdify
which converts the symbolic function to a regular Python function:
lam_f = sy.lambdify(rr, f(rr))
print(lam_f(7))
Usually such a function is used together with numpy to work on entire arrays in one go:
import numpy as np
print(lam_f(np.arange(1, 101)))
Upvotes: 2