2
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!

Tai
  • 7,684
  • 3
  • 29
  • 49
Bin
  • 209
  • 1
  • 3
  • 8

2 Answers2

5

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))
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
2

According to SymPy's documentation you have to evaluate the value of the function after substituting x with the desired value:

>>> dx.evalf(subs={x: 2})
4.00000000000000

or

>>> dx.evalf(2, subs={x: 2})
4.0

to limit the output to two digits.

Djib2011
  • 6,874
  • 5
  • 36
  • 41