Symbolic Math with Python
Many programming languages include libraries to do more complicated math. You can do statistics, numerical analysis or handle big numbers. One topic many programming languages have difficulty with is symbolic math. If you use Python though, you have access to sympy, the symbolic math library. Sympy is under constant development, and it's aiming to be a full-featured computer algebra system (CAS). It also is written completely in Python, so you won't need to install any extra requirements. You can download a source tarball or a git repository if you want the latest and greatest. Most distributions also provide a package for sympy for those of you less concerned about being bleeding-edge. Once it is installed, you will be able to access the sympy library in two ways. You can access it like any other library with the import statement. But, sympy also provides a binary called isympy that is modeled after ipython.
In its simplest mode, sympy can be used as a calculator. Sympy has built-in support for three numeric types: float, rational and integer. Float and integer are intuitive, but what is a rational? A rational number is made of a numerator and a denominator. So, Rational(5,2) is equivalent to 5/2. There is also support for complex numbers. The imaginary part of a complex number is tagged with the constant I. So, a basic complex number is:
a + b*I
You can get the imaginary part with "im", and the real part with "re". You need to tell functions explicitly when they need to deal with complex numbers. For example, when doing a basic expansion, you get:
exp(I*x).expand() exp(I*x)
To get the actual expansion, you need to tell expand that it is dealing
with complex numbers. This would look like:
exp(I*x).expand(complex=True)
All of the standard arithmetic operators, like addition, multiplication
and power are available. All of the usual functions also are available,
like trigonometric functions, special functions and so on. Special
constants, like e and pi, are treated symbolically in sympy. They
won't actually evaluate to a number, so something like "1+pi" remains
"1+pi". You actually have to use evalf explicitly to get a numeric
value. There is also a class, called oo, which represents the concept
of infinity—a handy extra when doing more complicated mathematics.
Although this is useful, the real power of a CAS is the ability to do symbolic mathematics, like calculus or solving equations. Most other CASes automatically create symbolic variables when you use them. In sympy, these symbolic entities exist as classes, so you need to create them explicitly. You create them by using:
x = Symbol('x')
y = Symbol('y')
If you have more than one symbol at a time to define, you can use:
x,y = symbols('x', 'y')
Then, you can use them in other operations, like looking at equations. For example:
(x+y)**2
You then can apply operations to these equations, like expanding it:
((x+y)**2).expand()
x**2 + 2*x*y + y**2
You also can substitute these variables for other variables, or even numbers, using the substitution operator. For example:
((x+y)**2).subs(x,1)
(1+y)**2
You can decompose or combine more complicated equations too. For example, let's say you have the following:
(x+1)/(x-1)
Then, you can do a partial fraction decomposition with:
apart((x+1)/(x-1),x)
1 + 2/(x-1)
You can combine things back together again with:
together(1 + 2/(x-1))
(x+1)/(x-1)
When dealing with trigonometric functions, you need to tell operators like
expand and together about it. For example, you could use:
sin(x+y).expand(trig=True)
sin(x)*cos(y) + sin(y)*cos(x)
The really big use case for a CAS is calculus. Calculus is the backbone of
scientific calculations and is used in many situations. One of the
fundamental ideas in calculus is the limit. Sympy provides a function
called limit to handle exactly that. You need to provide a function, a
variable and the value toward which the limit is being calculated. So, if
you wanted to calculate the limit of (sin(x)/x) as x goes to 0, you would
use:
limit(sin(x)/x, x, 0)
1
Because sympy provides an infinity object, you can calculate limits as they go to infinity. So, you can calculate:
limit(1/x, x, oo)
0
Sympy also allows you to do differentiation. It can understand basic polynomials, as well as trigonometric functions. If you wanted to differentiate sin(x), then you could use:
x = Symbol('x')
diff(sin(x), x)
cos(x)
You can calculate higher derivatives by adding an extra parameter to the
diff function call. So, calculating the first derivative of (x**2) can be
done with:
diff(x**2, x, 1)
2*x
While the second derivative can be done with:
diff(x**2, x, 2)
2
Sympy provides for calculating solutions to differential equations. You can
define a differential equation with the diff function. For example:
f(x).diff(x,x) + f(x)
where f(x) is the function of interest, and
diff(x,x) takes the second
derivative of f(x) with respect to x. To solve this equation, you would use
the function dsolve:
dsolve(f(x).diff(x,x) + f(x), f(x))
f(x) = C1*cos(x) + C2*sin(x)
This is a very common task in scientific calculations.
Joey Bernard has a background in both physics and computer science. This serves him well in his day job as a computational research consultant at the University of New Brunswick. He also teaches computational physics and parallel programming.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.
Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.
Sponsored by ActiveState
| Non-Linux FOSS: libnotify, OS X Style | Jun 18, 2013 |
| Containers—Not Virtual Machines—Are the Future Cloud | Jun 17, 2013 |
| Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer | Jun 12, 2013 |
| Weechat, Irssi's Little Brother | Jun 11, 2013 |
| One Tail Just Isn't Enough | Jun 07, 2013 |
| Introduction to MapReduce with Hadoop on Linux | Jun 05, 2013 |
- Containers—Not Virtual Machines—Are the Future Cloud
- Non-Linux FOSS: libnotify, OS X Style
- Linux Systems Administrator
- Validate an E-Mail Address with PHP, the Right Way
- Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer
- Senior Perl Developer
- Technical Support Rep
- RSS Feeds
- Introduction to MapReduce with Hadoop on Linux
- UX Designer
- Bought photoshop CS5 for developing a website :(
45 min 50 sec ago - What the author describes
2 hours 11 min ago - Reply to comment | Linux Journal
6 hours 22 min ago - Reply to comment | Linux Journal
7 hours 7 min ago - Didn't read
7 hours 17 min ago - Reply to comment | Linux Journal
7 hours 22 min ago - Poul-Henning Kamp: welcome to
9 hours 32 min ago - This has already been done
9 hours 33 min ago - Reply to comment | Linux Journal
10 hours 19 min ago - Welcome to 1998
11 hours 7 min ago
Featured Jobs
| Linux Systems Administrator | Houston and Austin, Texas | Host Gator |
| Senior Perl Developer | Austin, Texas | Host Gator |
| Technical Support Rep | Houston and Austin, Texas | Host Gator |
| UX Designer | Austin, Texas | Host Gator |
| Web & UI Developer (JavaScript & j Query) | Austin, Texas | Host Gator |
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?



Comments
It sound that this is a
It sound that this is a perfect combination between mobile phones and automotive, no doubt, android industries have begun to enter our life, and I have been thinking recently, if Obd2 auto diagnostic software can be integrated into mobile applications, it will greatly change our lives, and even bring about a revolution again. Now many shop began selling android Obd2 auto diagnostic software product, I was no exception, welcome to my shop to see what the latest android Obd2 auto diagnostic software products. car diagnostic tool
Formula correction
Liked the article: short, to the point and offering a useful introduction. A worthy mention regarding the pretty printing options is that there is also the MathML output option, for those wanting to publish online. But you could also load the sympy environment in the IPython notebook then and have IPython render your formulas with Mathjax.
Just wanted to point out a small typo for the integration of exp(x) too:
In [3]: integrate(exp(x), (x, 0, oo))
Out[3]: ∞
In [4]: integrate(exp(-x), (x, 0, oo))
Out[4]: 1