Function composition for user-defined functions

338 views
Skip to first unread message

Amit Saha

unread,
Jan 2, 2015, 9:21:37 AM1/2/15
to sy...@googlegroups.com
Hi all,

I understand that the compose() function defined in
sympy.polys.polytools can be used as follows:

>>> from sympy import compose, Symbol
>>> x = Symbol('x')
>>> compose(x+1, x+1)
x + 2


Now, let's say I have a user defined function defined as follows:

from sympy import Function, Symbol, solve, compose, sin, cos

class fx(Function):

@classmethod
def eval(cls, x):
return x**2

def _eval_evalf(self, prec):
return self.eval()

I tried to use the compose() function as follows:

compose(fx(x), x+1) and I get the answer as follows, x**2 + 2*x + 1
which is correct.

Is this the best way to demonstrate function composition for user
defined functions?

Thanks,
Amit.


--
http://echorand.me

Aaron Meurer

unread,
Jan 4, 2015, 2:29:58 PM1/4/15
to sy...@googlegroups.com
That only works because fx(x) always gives x**2. If it gave anything other than a polynomial (e.g., being unevaluated), it wouldn't. 

compose() is polynomial function. It's designed to efficiently compose two polynomials and expand the result. compose(a, b) is effectively the same as a.subs(x, b).expand(), but more efficient.

For general functions, I would just use subs, or Subs if you want something unevaluated.

Aaron Meurer
 

Thanks,
Amit.


--
http://echorand.me

--
You received this message because you are subscribed to the Google Groups "sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
To post to this group, send email to sy...@googlegroups.com.
Visit this group at http://groups.google.com/group/sympy.
To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/CANODV3%3DzF5hKDpTrLi0V-LO72AjQbDyUpMEUmy7v_E5GdprGew%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages