DEV Community

Erik
Erik

Posted on

Derivative Python Calculate Derivative Functions in Python

There are so many cool things you can do in Python, and today we're going to learn about calculating derivatives.

What's a Derivative

Remember Calculus 1? Me neither, so let's do a quick refresher.

Derivatives are how you calculate a function's rate of change at a given point. For example, acceleration is the derivative of speed. If you have a function that can be expressed as f(x) = 2x^2 + 3 then the derivative of that function, or the rate at which that function is changing, can be calculated with f'(x) = 4x.

Note: In case you don't know, the f'(x) is pronounced "f prime of x"

Derivatives have a lot of use in tons of fields, but if you're trying to figure out how to calculate one with Python, you probably don't need much more explanation from me, so lets just dive in.

Fire up that Python Console

If you don't already have the SymPy library, go ahead and run pip install sympy. SymPy is a Python library aiming to become a full fledged Computer Algebra System (CAS) which is a really freaking cool thing in its own right, but lets press on. First, let's get everything set up:

>>> from sympy import *
>>> # We have to create a "symbol" called x
>>> x = Symbol('x')
Enter fullscreen mode Exit fullscreen mode

Now that we've imported the library and created a symbol, let's make the function for 2x^2 + 3 (the math function, not a Python function):

>>> f = 2*x**2+3
>>> f_prime = f.diff(x)
Enter fullscreen mode Exit fullscreen mode

And what do these look like?

>>> f
2*x**2+3
>>> f_prime
4*x
Enter fullscreen mode Exit fullscreen mode

And that's all there really is to it. But those aren't actual functions, so what good are they to me unless I'm just trying to cheat on my homework? If I were writing a program that went through the trouble of finding a derivative, I'm probably intending to use it as a function, right? Well, SymPy has your back with a handy function called lambdify in which we pass our symbol and (math) function:

>>> f = lambdify(x, f)
>>> f_prime = lambdify(x, f_prime)
>>> # Let's test it out
>>> f(3)
21
>>> f_prime(3)
12
Enter fullscreen mode Exit fullscreen mode

And there you have it. So easy, right??

Conclusion

If you made it this far into the article and you're thinking to yourself "I will literally never use this" consider this: If there is a Python library for finding derivatives and then turning them into functions, there is probably a library for anything you might need. If you ever find yourself about to take on a really complex task, or you have a great idea for an application but are afraid the underlying implementation will be too much to write on your own, do a quick Google search and see if there isn't something out there already.

Happy coding! And as always, let me know if you have any questions.

Top comments (0)