0

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.

Reef
  • 35
  • 5
  • What do you want to achieve? Why do you call your function `derive`? Why do you think using `lambdify` would be useful in your approach? Writing something like `x = symbols(x)` is extremely confusing, and should be avoided; please don' t reuse the variable name there. – JohanC Sep 26 '21 at 20:44
  • the reason i wanted to write a function in that way is this: in machine learning, there are several steps for calculating a derivative of a given function (using pytorch). hence i wanted to create the above function (though incomplete) where one of its parameters is the function to be differentiated. For example, derive(5, x**2) would give 2*x=10. – Reef Sep 27 '21 at 13:03

1 Answers1

1

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()

plotting the derivative

JohanC
  • 71,591
  • 8
  • 33
  • 66