Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Applying Math with Python

You're reading from   Applying Math with Python Over 70 practical recipes for solving real-world computational math problems

Arrow left icon
Product type Paperback
Published in Dec 2022
Publisher Packt
ISBN-13 9781804618370
Length 376 pages
Edition 2nd Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
Sam Morley Sam Morley
Author Profile Icon Sam Morley
Sam Morley
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Chapter 1: An Introduction to Basic Packages, Functions, and Concepts 2. Chapter 2: Mathematical Plotting with Matplotlib FREE CHAPTER 3. Chapter 3: Calculus and Differential Equations 4. Chapter 4: Working with Randomness and Probability 5. Chapter 5: Working with Trees and Networks 6. Chapter 6: Working with Data and Statistics 7. Chapter 7: Using Regression and Forecasting 8. Chapter 8: Geometric Problems 9. Chapter 9: Finding Optimal Solutions 10. Chapter 10: Improving Your Productivity 11. Index 12. Other Books You May Enjoy

Differentiating and integrating symbolically using SymPy

At some point, you may have to differentiate a function that is not a simple polynomial, and you may need to do this in some kind of automated fashion—for example, if you are writing software for education. The Python scientific stack includes a package called SymPy, which allows us to create and manipulate symbolic mathematical expressions within Python. In particular, SymPy can perform differentiation and integration of symbolic functions, just like a mathematician.

In this recipe, we will create a symbolic function and then differentiate and integrate this function using the SymPy library.

Getting ready

Unlike some of the other scientific Python packages, there does not seem to be a standard alias under which SymPy is imported in the literature. Instead, the documentation uses a star import at several points, which is not in line with the PEP8 style guide. This is possibly to make the mathematical expressions more natural. We will simply import the module under its name sympy, to avoid any confusion with the scipy package’s standard abbreviation, sp (which is the natural choice for sympy too):

import sympy

In this recipe, we will define a symbolic expression that represents the following function:

Then, we will see how to symbolically differentiate and integrate this function.

How to do it...

Differentiating and integrating symbolically (as you would do by hand) is very easy using the SymPy package. Follow these steps to see how it is done:

  1. Once SymPy is imported, we define the symbols that will appear in our expressions. This is a Python object that has no particular value, just like a mathematical variable, but can be used in formulas and expressions to represent many different values simultaneously. For this recipe, we need only define a symbol for , since we will only require constant (literal) symbols and functions in addition to this. We use the symbols routine from sympy to define a new symbol. To keep the notation simple, we will name this new symbol x:
    x = sympy.symbols('x')
  2. The symbols defined using the symbols function support all of the arithmetic operations, so we can construct the expression directly using the symbol x we just defined:
    f = (x**2 - 2*x)*sympy.exp(3 - x)
  3. Now, we can use the symbolic calculus capabilities of SymPy to compute the derivative of f—that is, differentiate f. We do this using the diff routine in sympy, which differentiates a symbolic expression with respect to a specified symbol and returns an expression for the derivative. This is often not expressed in its simplest form, so we use the sympy.simplify routine to simplify the result:
    fp = sympy.simplify(sympy.diff(f))
    print(fp)  # (-x**2 + 4*x - 2)*exp(3 - x)
  4. We can check whether the result of the symbolic differentiation using SymPy is correct, compared to the derivative computed by hand using the product rule, defined as a SymPy expression, as follows:
    fp2 = (2*x - 2)*sympy.exp(3 - x) - (
        x**2 - 2*x)*sympy.exp(3 - x)
  5. SymPy equality tests whether two expressions are equal, but not whether they are symbolically equivalent. Therefore, we must first simplify the difference of the two statements we wish to test and test for equality to 0:
    print(sympy.simplify(fp2 - fp) == 0)  # True
  6. We can integrate the derivative fp using SymPy by using the integrate function and check that this is again equal to f. It is a good idea to also provide the symbol with which the integration is to be performed by providing it as the second optional argument:
    F = sympy.integrate(fp, x)
    print(F)  # (x**2 - 2*x)*exp(3 - x)

As we can see, the result of integrating the derivative fp gives back the original function f (although we are technically missing the constant of integration ).

How it works...

SymPy defines various classes to represent certain kinds of expressions. For example, symbols, represented by the Symbol class, are examples of atomic expressions. Expressions are built up in a similar way to how Python builds an abstract syntax tree from source code. These expression objects can then be manipulated using methods and standard arithmetic operations.

SymPy also defines standard mathematical functions that can operate on Symbol objects to create symbolic expressions. The most important feature is the ability to perform symbolic calculus—rather than the numerical calculus that we explore in the remainder of this chapter—and give exact (sometimes called analytic) solutions to calculus problems.

The diff routine from the SymPy package performs differentiation on these symbolic expressions. The result of this routine is usually not in its simplest form, which is why we used the simplify routine to simplify the derivative in the recipe. The integrate routine symbolically integrates a scipy expression with respect to a given symbol. (The diff routine also accepts a symbol argument that specifies the symbol for differentiating against.) This returns an expression whose derivative is the original expression. This routine does not add a constant of integration, which is good practice when doing integrals by hand.

There’s more...

SymPy can do much more than simple algebra and calculus. There are submodules for various areas of mathematics, such as number theory, geometry, and other discrete mathematics (such as combinatorics).

SymPy expressions (and functions) can be built into Python functions that can be applied to NumPy arrays. This is done using the lambdify routine from the sympy.utilities module. This converts a SymPy expression to a numerical expression that uses the NumPy equivalents of the SymPy standard functions to evaluate the expressions numerically. The result is similar to defining a Python Lambda, hence the name. For example, we could convert the function and derivative from this recipe into Python functions using this routine:

from sympy.utilities import lambdify
lam_f = lambdify(x, f)
lam_fp = lambdify(x, fp)

The lambdify routine takes two arguments. The first is the variables to be provided, x in the previous code block, and the second is the expression to be evaluated when this function is called. For example, we can evaluate the lambdified SymPy expressions defined previously as if they were ordinary Python functions:

lam_f(4)  # 2.9430355293715387
lam_fp(7)  # -0.4212596944408861

We can even evaluate these lambdified expressions on NumPy arrays (as usual, with NumPy imported as np):

lam_f(np.array([0, 1, 2]))  # array([ 0. , -7.3890561, 0. ])

Note

The lambdify routine uses the Python exec routine to execute the code, so it should not be used with unsanitized input.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image