Ask Your Question
0

convert a lambdified expression to a function

asked 2023-01-30 16:08:12 +0100

moon gravatar image

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 flag offensive close merge delete

Comments

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,

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2023-01-30 21:01:32 +0100 )edit

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

moon gravatar imagemoon ( 2023-01-30 22:05:15 +0100 )edit

1 Answer

Sort by » oldest newest most voted
1

answered 2023-01-30 21:15:00 +0100

rburing gravatar image

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.

edit flag offensive delete link more

Comments

Appreciated !

moon gravatar imagemoon ( 2023-01-30 22:05:51 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2023-01-30 16:08:12 +0100

Seen: 431 times

Last updated: Jan 30 '23