chapter ten

10 Working with Symbolic Expressions

 

This chapter covers

  • Modeling algebraic expressions as data structures in Python
  • Writing code to analyze, transform, or evaluate an algebraic expression
  • Finding the derivative of a function by manipulating the expression that defines it
  • Writing a Python function to take derivatives automatically
  • Using the SymPy library to take integrals automatically

In your programming career, you’ve probably thought of functions as small programs.  They are self-contained sets of instructions that accept some input data, do some ordered computations with it, and identify some result value as an output.  In this book I’ve promoted the functional perspective, where we consider functions pieces of data themselves.  You’ve now seen a number of functions that take other functions as input, or that produce functions as output.

In most of our examples so far, we’ve produced new functions from old ones by composing them, partially applying them, or calling them multiple times.  What we haven’t yet covered is how to compute facts about functions.  Say we have a mathematical function like:

f(x) = (3x2+x)sin(x)

We can easily translate it to Python:

from math import sin
 def f(x):
     return (3*x**2 + x) * sin(x)

10.1   Modeling algebraic expressions

10.1.1   Breaking an expression into pieces

10.1.2   Building an expression tree

10.1.3   Translating the expression tree to Python

10.1.4   Exercises

10.2   Putting a symbolic expression to work

10.2.1   Finding all the variables in an expression

10.2.2   Evaluating an expression

10.2.3   Expanding an expression

10.2.4   Exercises

10.3   Finding the derivative of a function

10.3.1   Derivatives of powers

10.3.2   Derivatives of transformed functions

10.3.3   Derivatives of some special functions

10.3.4   Derivatives of products and compositions

10.3.5   Exercises

10.4   Taking derivatives automatically

10.4.1   Implementing a derivative method for expressions