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) 

About janpenguin

Email: janpenguin [at] riseup [dot] net Every content on the blog is made by Free and Open Source Software in GNU/Linux.
This entry was posted in Python and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s