In a previous post, I examined Maxima, a free computer algebra system (CAS). Yesterday I discovered SymPy, a Python library that adds CAS functionality to the Python language, and decided to give it the same test drive I gave Maxima. I report the results here, and then provide a brief summary of why using CAS functionality in Python offers advantage over using a stand-alone CAS program such as Maxima.
We first specify the normal density function as a SymPy object and integrate to verify that the area under the curve equals one:
We then calculate the first moment of the normal density function and verify that it equals the mean. Note that we have to explicitly simplify the result to see it clearly:
Next, we compute the second moment and the variance, to ensure the variance equals sigma squared:
Moment calculations such as those shown above are often simplified through use of moment generating functions, which gives us an opportunity to test differentiation:
Here we see that the correct first and second moments are generated.
In all our integrations above, we used the “conds=’none’” option. This turns off reporting of the convergence conditions in the result, which when reported makes the output unwieldy. The following screenshot shows the area under the curve computation with and without this option in effect:
As you can see, when convergence conditions are calculated, the value of one shows up as part of a SymPy “Piecewise” function. (The value is immediately to the right of the word “Piecewise”). When the convergence conditions are left out, we get manageable results.
The Python Advantage
SymPy offers advantage over Maxima in that it uses Python syntax and idioms, which means that users familiar with Python can immediately grok it. This is especially beneficial since Python is easy to learn and easy to work with. Furthermore, since Python is a full functioning programming language, users can combine SymPy analysis with use of other Python libraries such as Numpy/SciPy/Matplotlib for numerical analysis and Django for web production.