from sympy import *
x = Symbol('x')
y = x ** 2
dx = diff(y, x)
This code can get the derivative of y.
It's easy dx = 2 * x
Now I want to get the value of dx
for x = 2
.
Clearly, dx = 2 * 2 = 4
when x = 2
But how can I realize this with python codes?
Thanks for your help!
Probably the most versatile way is to lambdify
:
sympy.lambdify
creates and returns a function that you can assign to a name, and call, like any other python callable.
from sympy import *
x = Symbol('x')
y = x**2
dx = diff(y, x)
print(dx, dx.subs(x, 2)) # this substitutes 2 for x as suggested by @BugKiller in the comments
ddx = lambdify(x, dx) # this creates a function that you can call
print(ddx(2))