8

I want to do something like h = f(g(x)) and be able to differentiate h, like h.diff(x). For just one function like h = cos(x) this is in fact possible and the documentation makes it clear.

But for function compositions it is not so clear. If you have done this, kindly show me an example or link me to the relevant document.

(If Sympy can't do this, do you know of any other packages that does this, even if it is non-python)

thank you.

user1521607
  • 321
  • 1
  • 4
  • 12
  • Can you provide an example of "function compositions" were you can't achieve your goal? – user Jun 10 '15 at 10:43
  • I can't!, I am gonna accept the @maxymoo answer, looks like sympy has an SEO problem, it would be good if they make another page - call it composition and link it to the same substitution page with an example like maxymoo's. In regular math, substitution and composition are very different animals. – user1521607 Jun 10 '15 at 20:04

2 Answers2

11

It seems that function composition works as you would expect in sympy:

import sympy
h = sympy.cos('x')
g = sympy.sin(h)
g
Out[245]: sin(cos(x))

Or if you prefer

from sympy.abc import x,y
g = sympy.sin('y')
f = g.subs({'y':h})

Then you can just call diff to get your derivative.

g.diff()
Out[246]: -sin(x)*cos(cos(x))
maxymoo
  • 35,286
  • 11
  • 92
  • 119
  • This looks like a substitution. I am looking for this form: h = sympy.cos('x'); g = sympy.sin('y'); f = g(h); f.diff() – user1521607 Jun 04 '15 at 08:08
  • 1
    but a function composition **is** a substitution. If it makes it clearer, I've added an alternate syntax that you can use. – maxymoo Jun 04 '15 at 08:13
2

It's named compose; although, I can't find it in the docs.

from sympy import Symbol, compose
x = Symbol('x')
f = x**2 + 2
g = x**2 + 1

compose(f,g)
Out: x**4 + 2*x**2 + 4
unDeadHerbs
  • 1,306
  • 1
  • 11
  • 19
  • This won't work with functions that aren't polynomials. See https://stackoverflow.com/a/73779580/3004881 – Dan Getz Sep 19 '22 at 23:41