Math-Intensive Reports with GNU Emacs and Calc, Part 1

by Charles L. III

I'm trained as an engineer, and I work in the structural analysis field. As part of my job, I have to perform structural stress analyses and document the results in reports. For me, GNU Emacs has solved several longstanding problems related to the authoring and publication of such reports.

The unique situation that engineering analysts like me encounter is preliminary engineering calculation reports must be written at specific points in time as an engineering project evolves. These preliminary reports must be complete and accurate relative to the current state of the design, even if the design itself is still incomplete and in flux. Such reports are required by contract to be delivered to design review meetings as an integral part of the in-process documentation of a design. They are checked by the customer's representatives, and if problems are found (either with the hardware as exposed by the analysis or with the analysis report itself), they must be corrected right away. This is a different matter considering the problem of writing papers whose accuracy is checked only once before publication in a scholarly journal.

I know other engineers (of whatever specialty area) experience the same problems, and I believe they will be interested in learning about useful software tools that can solve them. In fact, almost anyone who needs to write reports documenting on-going calculations should find this article to be of use.

I have only recently started using Emacs. In fact, this article evolved from numerous small text files I'd made for testing various aspects of Emacs. For years I had been intrigued by what I'd heard about it, but I also felt intimidated by its legendary size and complexity. Three things finally compelled me to buckle down and try Emacs. The first was my discovery that Emacs is actually quite small compared to the average late-1990s word processor installation. The second was a sense of revulsion that overcame me when my favorite word processor, WordPerfect, was consigned to the scrap heap of history by a notably inferior product being pushed along by a marketing juggernaut. The third and most important was calc.el, the Elisp Calc math package. Today, having become fairly comfortable with Emacs+Calc, I am not looking back.

Why Numbers Alone Are Not Enough

If you do math, you probably recognize that it's not only about the numbers. It's about your assumptions, your mathematical model of reality, your results, your interpretation and understanding of them and your ability to make them clear to other readers. It's about leaving behind a record of what you did and why you did it, so others can review, comment on, criticize and update what your work. Only in this way can a calculation carry any significance. In short, I am talking about a report.

Whether it's figuring out your car's gas mileage or the best way to intercept an incoming asteroid, you need to keep a record for yourself as well as for others. Therefore, you need to write a report. It may be only a few sentences, or it could be a thousand pages. It may be only for yourself, if you think you might have trouble remembering what you did, or it may be to convince NASA authorities to accept your science payload for a ride on the Space Shuttle. While you alone are responsible for calculating your car's miles per gallon, your calculations of the structural integrity of a Shuttle payload affect, and are affected by, a great many people. In cases like these, a formal report is absolutely required.

The great bugaboo with all such reports, however, is the need to track changes. The calculation results need to be updated every time design changes are made, and the report must be reissued for design review meetings. What kinds of design changes? Many: changes in dimensions, material specifications, the manner of attaching and fastening parts, numbers and sizes of bolts and screws and estimated loading cases, to mention a few. In an engineering design project, redesigns come almost hourly in the early phases. Later on, as the design becomes more mature, things stabilize a bit, and the rate at which design changes occurs drops dramatically. The problem is, by this time in the project, you have generated many pages of extremely detailed analyses. Coping with even a minor change can set your publication date back by weeks. Keeping a stress calculation report current, based on the latest design information, is a massive headache. Enter Emacs+Calc.

Why Is Emacs so Important?

Emacs is described by its author as an "extensible, customizable, self-documenting real-time display editor". Emacs is written almost entirely in its own version of the Lisp language (Emacs Lisp, or elisp). Elisp is a general-purpose programming language. Almost all of Emacs' built-in editing functions are implemented as calls to a predefined library of elisp functions. Emacs is extensible because expert users can write full-fledged application program libraries in elisp. Once a useful elisp library or application program has been written and tested, it becomes available to any user of Emacs, whether or not he knows elisp. Indeed, the Emacs distribution comes with a great many elisp packages, and many more are available from various sources on the Internet.

If you have ever used the Autocad drafting package, you'll know that it also uses an embedded version of Lisp (Autolisp) as a medium for writing all kinds of extensions. There is a lively trade in Autolisp libraries and applications among the worldwide body of Autocad users. Not all of these users know how to write anything at all in Autolisp, but one doesn't need to know Autolisp simply to use an Autolisp add-on package. It's the same way with Emacs and elisp.

Using elisp software, it is possible to use Emacs as your primary user interface to a computer system. Emacs' elisp packages make it possible to:

  • send and receive e-mail;

  • post and read NNTP news messages;

  • launch programs on both local and remote computers;

  • send data to programs and view the output;

  • browse the World Wide Web;

  • upload and download files with FTP;

  • remotely operate computers via Telnet or SSH;

  • fill out on-line forms and interact with databases;

  • create gorgeous print documents with LaTeX or groff;

  • create and manipulate XML data and documents; and

  • perform simple and fancy mathematics.

All this is done without leaving Emacs.

Where Does Calc Fit In?

Calc is an elisp package originally written by Dave Gillespie. Lately, however, many others have contributed to its development in the classical manner: hackers working over the Internet. Once it has been downloaded and installed in your local emacsen directory (the place where elisp add-on packages live) and a few lines have been added to your .emacs configuration file, Calc becomes an invisible math miracle worker. In any Emacs buffers you choose, you can slip quickly and silently into and out of Calc mode (any of several such modes, really) with a simple keystroke or two.

A Simple Example of Calc

Let's do a simple calculation of a right triangle. If the two short legs are denoted a and b, where (say)

$ a := 3.1 $


$ b := 4.1 $

then the length of the hypotenuse is

$ c := sqrt(a^2 + b^2) => 5.14003891036 $.

I didn't have to get my calculator out to do this. I did it right inside Emacs. Furthermore, this file is live. That means in order to update the calculation for an arbitrary right triangle, all I have to do is is change the values assigned to a, b or both, position the cursor inside the first formula and type M-# e (M for Meta, the Alt key on most PCs; the keystroke sequence therefore is Alt-# e, which is Alt-Shift-3 e). The Calc package loads up, and the value of c is immediately updated.

Now that I have the variables a, b and c defined, I can use their values over and over:

     $ a + b + c => 12.3400389104 $     (the perimeter)
     $ a^2 + b^2 - c^2 => 0. $          (a check on the calculation)
What This Article Is and Is Not

I am going to provide you with a short and incomplete survey of Emacs' ability to perform mathematical and numerical evaluations like my examples, right in the editing buffer, by means of Calc.

I do not intend to explain in detail how to download, install or use Emacs (although the Resources section gives some pointers). Nor do I intend to waste words disparaging other editors (such as vi), nor browbeat their users about the superiority of Emacs. And I won't go into any real detail on how to start up the Calc package, nor will I delve deeply into the keystroke sequences needed to cause Calc to perform its magic. All that stuff is documented elsewhere; you simply need to make your decision to learn Emacs. What I am going to show you are some astounding (and generally unknown) capabilities of Emacs for performing mathematical analysis, courtesy of Calc.

What You Need

To have the capability to write live ASCII math documents, you and your computer must have a few required pieces:

  • An environment that is capable of running Emacs;

  • Emacs itself, installed and configured to your taste;

  • The calc.el math plug-in (I suppose we could call it that) installed in your local emacsen directory; and

  • Some practice using Emacs.

Emacs is basically a UNIX program, but it has been written carefully so it may be ported to other operating systems. Versions are available for almost every computing platform in existence: all known Unices and UNIX workalikes (such as Linux and BSD); all versions of Windows since Windows 95; UNIX-like environments, such as the Cygwin tools, that run under Windows; and various other platforms and operating systems as well.

If you run UNIX or Linux, Emacs is probably already available on your system; type emacs at the command prompt and see if it pops up. If it doesn't, it is a simple download away; see the Resources.

If you are a Windows user, you will need to download and install the Windows version of Emacs, called NTEmacs. It is a standard Windows-style self-installing executable. If you are using the Cygwin tools under Windows, be aware that NTEmacs doesn't build under that UNIX-like package but does work well with it.

Next, you need the Calc package, known by the filename calc.el. Download and install it (see Resources), and you can then turn on the calculator any time you are editing by using the M-# keyboard command.

Further Motivation

Here is another example, one that is somewhat close to home for me. I am going to calculate some cross-sectional area properties for a beam. Let's say the beam's cross section is rectangular, of height "height" and width "width". (Of course, I have obtained all the dimensional information from the preliminary engineering drawings.) I merely type the following Calc assignments into my editing buffer (that is to say, directly into the window that shows the article I am writing now):

     $ height := 0.65 in $
     $ width := 0.25 in $

(I am including units here; the dimensions are in inches.) Then I can start Calc and perform the following calculations. First, I need the cross sectional area of the beam. I enter

$ area := width height => $

Then I type M-# u, u for update, and I immediately see the ab ve line change to this:

$ area := width height => 0.1625 in^2 $

The answer, complete with derived units, pops up on my editing screen, to the right of the => symbol.

Later on, I'll need to use these results to calculate bending stresses. To do that, I first have to calculate the moment of inertia (MI) of the cross section. Without getting into the details, the moment of inertia is an important geometric property of a beam. (The following formula is correct only for a rectangular cross section.)

$ MI := width height^3 / 12. => 5.72135416667e-3 in^4 $

For many purposes, the section modulus Z is a more useful number. For this simple rectangular cross section, it is equal to the moment of inertia divided by half the section height:

$ Z := 2. MI / height => 0.0176041666666 in^3 $

I did this example in about one minute, entirely inside my editor's screen buffer. And I did not have to use any other program to perform these calculations---only Emacs and Calc, working smoothly together.

A few explanations are in order to help you read this and the following examples:

  1. I am using the embedded mode of Calc, which evaluates the formulas in the buffer where they are written. (Other modes of operation are available that show you a calculator pop-up screen or a stack. I won't be using those modes because they are not so useful for reports.)

  2. Formulas are bracketed by dollar signs to facilitate recognition by Calc (other syntactical conventions are also supported).

  3. Multiplication is indicated by adjacency of the factors ("width height" is width times height). Whitespace must separate the factors.

  4. => is the evaluates-to operator; in embedded mode, the value of the expression on its left is inserted on its right.

  5. := is an assignment operator. The variable on its left receives the value on its right, and that variable can be used in future calculations.

Calc Does Units

Notice that my example kept track of units. It's able to do so because Calc also can perform symbolic algebra (a subject far too large for this small article) and treats the symbol "in" (inches) as an undetermined factor. Special operations are available to convert units. Calc knows about units and their conversion. For example, how many pints does a lake having 11,000 acre-feet of water contain? To find out, I first write out the volume in the given units:

$ WaterVolume := 11000. acre ft $

Now, if I type the expression WaterVolume => and evaluate it, I get this:

$ WaterVolume => 11000. acre ft $

Exactly what I typed in. Next, by putting the cursor over the acre unit, selecting (with j s and <codej m commands) the units expression (11000. acre ft) and invoking u c (units-convert), Calc will ask me what type of unit should be used in the conversion. I respond pt. Then Calc immediately changes the previous expression to this:

$ WaterVolume => 28674925714.3 pt $

Obviously, Calc knows how to convert an acre-foot to pints, and doing so is much quicker than describing it.

You don't have to use units at all if you don't want to. If you carefully define all your units up front and use them consistently throughout your report, Calc won't have to do any units munging. But it is useful for converting weird commercial units; it can be handy for converting, say, gas pipeline flow rates in MMSCFD into pounds mass per second.

More examples of Emacs/Calc magic will be presented in Part 2 of this article.



General description:

FTP mirror list & instructions for downloading:

Emacs Wiki:






Cygwin Tools


User's Guide:

Emacs Lisp

The Emacs Lisp Archive:

The Emacs Lisp List:


Download code and documentation:


Download code and documentation:

Load Disqus comments