The answer to this question is pretty simple. Sure, the subs
option given in the other answer works for evaluating the derivative at a number, but it doesn't work if you want to plot the derivative. There is a way to fix this: lambdify, as explained below.
Use lambdify to convert all of the sympy functions (which can be differentiated but not evaluated) to their numpy counterparts (which can be evaluated, plotted, etc., but not differentiated). For example, sym.sin(x) will be replaced with np.sin(x). The idea is: define the function using sympy functions, differentiate as needed, and then define a new function which is the lambdified version of the original function.
As in the code below, sym.lambdify takes the following inputs:
sym.lambdify(variable, function(variable), "numpy")
The third input, "numpy", is what replaces sympy functions with their numpy counterparts. An example is:
def f(x):
return sym.cos(x)
def fprime(x):
return sym.diff(f(x),x)
fprimeLambdified = sym.lambdify(x,f(x),"numpy")
Then the function fprime(x)
returns -sym.sin(x)
, and the function fprimeLambdified(x)
returns -np.sin(x)
. We can "call"/evaluate fprimeLambdified
at specific input values now, whereas we cannot "call"/evaluate fprime
, since the former is composed of numpy expressions and the latter sympy expressions. In other words, it makes sense to input fprimelambdified(math.pi)
, and this will return an output, while fprime(math.pi)
will return an error.
An example of using sym.lambdify
in more than one variable is seen below.
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))