Reputation: 191
I cannot lambdify expression that contains derivatives. Here is the minimum code that explains the problem:
import sympy
x = sympy.symbols('x', real=True)
a = sympy.Function('a')(x)
b = a**2
r = sympy.diff(b, x)
sympy.lambdify((a), b) # works
r.evalf(subs={diff(a, x): 1, a: 2}) # works
b_x = sympy.lambdify((diff(a, x), a), r) # throws an error
The last line of code throws the following error:
Traceback (most recent call last): File "C:\Anaconda2\lib\site-packages\IPython\core\interactiveshell.py", line 2882, in run_code
exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-29-a0069a059795>", line 2, in <module>
gx = sympy.lambdify((diff(a, x), a), r) # gives an error File "C:\Anaconda2\lib\site-packages\sympy\utilities\lambdify.py", line 434, in lambdify
func = eval(lstr, namespace) File "<string>", line 1
lambda Derivative(a(x), x),_Dummy_29: (2*Derivative(_Dummy_29, x)*_Dummy_29)
^ SyntaxError: invalid syntax
Upvotes: 1
Views: 1738
Reputation: 879511
lambdify
attempts to replace symbolic functions with numerical equivalents and
return a function which can accept numeric values or arrays and return a number or array.
The error message
lambda Derivative(a(x), x),_Dummy_29: (2*Derivative(_Dummy_29, x)*_Dummy_29)
^ SyntaxError: invalid syntax
shows that lambdify is trying to build a lambda function whose first argument is Derivative(a(x), x)
. Clearly that's not going to work. We need a bare variable name instead of the symbolic expression Derivative(a(x), x)
.
So replace Derivative(a(x), x)
with a bare symbol, da
:
import sympy
x = sympy.symbols('x', real=True)
a = sympy.Function('a')(x)
b = a**2
r = sympy.diff(b, x)
da = sympy.symbols('da')
b_x = sympy.lambdify((da, a), r.subs([(sympy.diff(a, x), da)]))
assert b_x(1, 2) == r.evalf(subs={sympy.diff(a, x): 1, a: 2})
# 4
Upvotes: 4