Search code examples
pythonsympyderivative

How do I compute derivative of a lambda expression using Sympy?


How to compute a lambda expression's derivative ?

For example:

func = lambda x: x ** 3 - 3 * x ** 2
...
# the code
...
derived_func = lambda x: 3 * x ** 2 - 6 * x

Solution

  • You can call the lambda with a symbol as a parameter, and then differentiate the resulting expression:

    from sympy import *
    x = symbols('x')
    func = lambda x: x ** 3 - 3 * x ** 2
    display(func(x).diff(x))
    

    Result: 3*x**2 - 6*x