Basic Calculus with Python: Differentiation and Integration

I have to admit, I’m really excited whenever I googled “How to do <something> in python” and a Stackoverflow link–with a (solved) tag– come on top of the result page.

Star of today’s show is the sympy module: a library aimed at solving and displaying symbolic computation.

What is symbolic computation?

Ever had one of those moments where you type “2/7” into your scientific calculator, but being a stupid machine, it displays back the result of 2/7?

It’s not that it’s unhelpful, the calculator follows a principle where any results displayed must be an exact value. So instead of 1.41421356…–which is an approximation–it gives you the exact value of square root of 2.

Image source : me + MS Paint

Plus any mathematical expression (say ‘x’) with unevaluated value will be left as symbols (hence “symbolic”).

Let’s dive into an example.

First, import all function from the module

from sympy import * 
# * means we are importing all functions from the modul

Then add a symbol, in this case we pick the long-standing and the famous letter “x”

x = symbol('x') 
#this tells python that any subsequent mention of the letter x should be treated as a symbol

The next step is, of course, write a function, any function. Say y = x^3 + 2

y = x**3 + 2*x

The function needed to find derivatives is diff(). So you can go with y.diff() or diff(y), the result will be the same, which is

3*x**2 + 2

For integration, the function is integrate(). So again, either y.integrate() or integrate(y) will give you the same answer

.

Want to take it up a notch and integrate 2 or more variables? Easy

Just tell python all of the symbols you’re going to be using.

x,y = symbols(x y) 
#note the function used here is symbols, with an "s

Then the function

z = x**2 + y**2   
#if you pay attention in math class, this is an equation for a circle

The partial derivates–that means the other variable will be kept and treated as a constant–are

diff(z, x)
#with respect to x
#which will yield 2*x

diff(z, y)
#which will yield 2y
#with respect to y

The integral, with respect to x, is

integrate(z, x)
#which will yield x**3/3 + x*y**2

That’s it!

I will post more on the graphing part of calculus in the next post.

Leave a comment

Website Powered by WordPress.com.

Up ↑

Design a site like this with WordPress.com
Get started