user1521607
user1521607

Reputation: 351

How to do function composition in Sympy?

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.

Upvotes: 11

Views: 4180

Answers (2)

unDeadHerbs
unDeadHerbs

Reputation: 1403

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

Upvotes: 3

maxymoo
maxymoo

Reputation: 36545

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

Upvotes: 11

Related Questions