# convert a lambdified expression to a function

Hi there, Given an expression f uppon which I have no control (it means that it could be any univariate expression) example:

1/(x + 7) has the type: <class 'sympy.core.power.Pow'>


I need it to be of type function g so that can make some operations on it, therefore lambdified it g = lambdify(x, f) to get type(g)

<function _lambdifygenerated at 0x7fd435c06050> has the type: <class 'function'>


I need this to be a real function therefore, I checked that I can evaluate g, example g(1) This works fine. However if I wanted to calculate let's say the derivative derivative(g,x) then I get a monstruous error:

AttributeError                            Traceback (most recent call last)
Input In [27], in <cell line: 28>()
24 print(g(Integer(1)))
25 #print(derivative(g,x)) #This doesn't work too. error: TypeError: unable to convert <function _lambdifygenerated at 0x7fd435d4bb50> to a symbolic expression
26 #
27 #method 2: convert f to a function type
---> 28 h = eval(str(f)).function(x)
29 print(str(h) + " has the type: " + str(type(h)))
30 print(derivative(h,x))
AttributeError: 'Pow' object has no attribute 'function'


I also tried to do it like this g=eval(f).function(x) with no sucess I am in trouble looking for some help. Thanks in advance M

edit retag close merge delete

You seem to use Sympy, whereas this site is dedicated to the care and feeding of Sagemath (née Sage).

While Sage incorporates Sympy, use it and can (somewhat awkwardly) use it, your question may be asked on the Sympy list/forum with better chances of getting a significant answer.

HTH,

( 2023-01-30 21:01:32 +0200 )edit

Thanks for that. I'll also try what recommended below before moving elsewhere.

( 2023-01-30 22:05:15 +0200 )edit

Sort by » oldest newest most voted

If g is some callable version of an expression, then you should differentiate g(x) rather than g itself:

sage: from sympy import symbols, lambdify, diff
sage: x = symbols('x')
sage: f = int(1)/(x + int(7)) # avoid Sage integers, ensure the result is a SymPy object
sage: g = lambdify(x, f)
sage: g(1)
0.125
sage: diff(g(x), x)
-1.0/(x + 7)**2.0


The resulting SymPy expression object can be lambdified again if desired.

more

Appreciated !

( 2023-01-30 22:05:51 +0200 )edit