I'm trying to write a function that has a literal function as a parameter:
def derive(x, y):
x = symbols(x)
y = symbols(y)
return lambdify(x, y)
derive(5, 'x**2')
This returns a syntax error:
File "<lambdifygenerated-32>", line 1
def _lambdifygenerated(25.0):
^
SyntaxError: invalid syntax
If I write (outside the function scope):
f = lambdify(x, x**2) f(5)
it works. I appreciate any help on this.
In sympy you can get the derivative of a function via diff()
. .subs(x, 5)
fills in the value 5
for x
. An example:
from sympy.abc import x
f = x**2
print(f.diff(x).subs(x,5))
Here is how a function that would calculate the derivative of a given function at a given value could look like. evalf()
can be used to iron out symbolic parts (such as giving a numeric approximation for 2*pi
or Sqrt(5)
which sympy standard wants to keep in their exact symbolic form).
def derive_and_evaluate(x, f, xval):
return f.diff(x).subs(x, xval).evalf()
derive_and_evaluate(x, x**2, 5)
If you need the same derivative for a lot of x-values, you can do:
from sympy import lambdify
g = lambdify(x, f.diff(x)) # now `g` is a numpy function with one parameter
Or, if you want a function that does the derivation and converts to numpy form:
def derive_and_lambdify(x, f):
return lambdify(x, f.diff(x))
g = derive_and_lambdify(x, x**2)
print(g(5))
From then on, you can use g
similar to other numpy functions. Here is a more elaborate example:
from sympy import lambdify, sin
from sympy.abc import x
f = sin(1 / (1 + x ** 2))
g = lambdify(x, f.diff(x))
import numpy as np
from matplotlib import pyplot as plt
xs = np.linspace(-5, 5, 100)
ys = g(xs)
plt.plot(xs, ys)
plt.show()