## sympy – appling the chain rule manually to find derivative of a function.

I spent few hours to figure out how to apply the chain rule manually to find derivative of a function due to poor documentation of SymPy. I’m not that smart guy.

```from sympy import *

def pprints(func, *funcs):
breaker = '='*30
pprint(func)
print breaker
if funcs is None:
return

for f in funcs:
pprint(f)
print breaker

init_printing()

# Write the funcion in the form of y = f(u) and u = g(x). Then find dy/dx as a
# function of x.
# Exercise of the chain rule.

# 9. y = (2*x + 1)**5
u = symbols('u')
f = u**5
x = symbols('x')
g = 2*x + 1

# dy/dx = df/du * du/dx

# du/dx = dg/dx
dgdx = diff(g, x)
dudx = dgdx

# df/du
dfdu = diff(f, u)

# dy/dx
dydx = dfdu * dudx

# Make dy/dx as the function of x
# replace u with g(x)
pprints(f, g, dfdu, dgdx, dydx, dydx.subs(u, g))

# diff() is pretty smart!
y = (2*x + 1)**5
pprint(diff(y, x))

=== output ===
5
u
==============================
2⋅x + 1
==============================
4
5⋅u
==============================
2
==============================
4
10⋅u
==============================
4
10⋅(2⋅x + 1)
==============================
4
10⋅(2⋅x + 1)
```