Can I use lambdify to evaluate the derivative of a python function?

Viewed 4444

I asked a question yesterday regarding differentiating a python function and then when I found that none of the answers posted were satisfactory for my need of evaluating (in some variables) and then plotting the derivative, I was able to figure out my own solution.

Previous code:

import sympy as sym
import math


def f(x,y):
    return x**2 + x*y**2


x, y = sym.symbols('x y')

def fprime(x,y):
    return sym.diff(f(x,y),x)

print(fprime(x,y)) #This works.

print(fprime(1,1)) 

New code:

import sympy as sym
import math


def f(x,y):
    return x**2 + x*y**2


x, y = sym.symbols('x y')

def fprime(x,y):
    return sym.diff(f(x,y),x)

print(fprime(x,y)) #This works.

DerivativeOfF = sym.lambdify((x,y),fprime(x,y),"numpy")

print(DerivativeOfF(1,1))

As you can see, I overcame the inability to evaluate the derivative fprime by creating a new function DerivativeOfF which was the "lambdified" version of fprime. From there, I was able to evaluate DerivativeOfF, and also plot it in one of the variables.

My question is: why did this work? What exactly have I done? And what are some downsides to this method? I have tried reading the lambdify documentation but it's extremely confusing to me (I'm a beginner in Python). My guess is that I converted the Python function fprime to a Sympy expression DerivativeOfF, or something like that. Any help explaining what happened and why, and what exactly lambdify does (in layman's terms), would be appreciated.

3 Answers
Related