Showing posts with label Physics. Show all posts
Showing posts with label Physics. Show all posts

Wednesday, November 29, 2017

Six Ways to Measure Your Electricity Use

Maybe you want to save money. Maybe you want to save the planet. Maybe you just want to understand what’s going on inside your home. Or maybe, like me, you’re motivated in all three of these ways. Whatever the reason, let’s talk about how you can measure your household electricity use.

In this article I’ll describe six practical electricity measurement methods, starting with the simplest and progressing toward those that require more effort. Beginners will want to get comfortable with each method before moving on to the next. More advanced readers should feel free to skip ahead to the methods they don’t already know.

Ready? Here we go...

1. Look at your bills.

You probably receive an electricity bill every month. Of course the bill shows how much money you owe, but it also shows how much electricity you’ve used. (If your bill gets sent to a landlord who doesn’t let you see it, then you’ll have to skip this method and go on to the next one.)

Even if all you really care about is money, it’s not enough to look only at the dollar amount on your bill because that amount might not be a good measure of how much electricity you’ve used. It probably includes a base rate that you pay even if you use no electricity, and it might include other utilities besides electricity. Worse, your utility company might have you on an “equal billing” plan that averages your bill over the course of a year, hiding the interesting seasonal changes.

So you want to look on your bill for a number that’s not in dollars but rather in kilowatt-hours, or kWh for short. That number is the actual amount of electrical energy you used during the month. For example, here’s my bill from February 2014, during which I used 146 kWh:


Don’t be shocked if your monthly usage is a lot more than mine! According to official government data, the average American household uses nearly 900 kWh per month.

Besides comparing your monthly electricity use to the average American household (or, if you prefer, to my own), you can learn a lot by comparing to your own usage in other months. Look at a whole year’s worth of bills if you can, to see the seasonal patterns. Many Americans use the most electricity in the summer, when they use their air conditioners; others use the most in the winter, for heating and lighting.

What’s a kilowatt-hour anyway?

A kilowatt-hour is a unit for measuring energy, just as a mile is a unit for measuring distance and a dollar is a unit for measuring money. As with those other units, you’ll develop an intuitive feel for kilowatt-hours as you encounter more examples. Here are a few common household uses that typically consume approximately one kWh each:
  • Running a central air conditioner for 20 minutes
  • Running an electric space heater for 40 minutes
  • Running a modern no-frills refrigerator for one day
  • Baking a batch of cookies in an electric oven
  • Drying 1/3 of a load of laundry in an electric dryer
  • Leaving an LED light bulb on for a few days
  • Fully charging a laptop computer battery 10 times
And what does each of these activities cost? Most Americans pay between 10 and 20 cents for a kWh of electrical energy.

At some point you may want to compare electrical energy to other forms of energy, such as chemical energy (in food or fuels), or thermal energy (heat). Because we can convert one type of energy into another, we really should use the same unit to measure all types—but we don’t! Our inconvenient tradition is to measure food energy in Calories (abbreviated Cal, which scientists call large calories or kilocalories) and, here in the U.S., to measure heat in British thermal units (Btu). You can convert between kWh, Cal, and Btu using Google or various other web sites. The approximate conversion factors are
1 kWh = 860 Cal = 3400 Btu.
So the typical American consumes enough food to provide two to three kWh of energy each day (1700 to 2600 Cal), and a typical household furnace can provide about 22 kWh of heat each hour (75,000 Btu). A gallon of gasoline, if you’re curious, provides about 31,000 Cal, or 120,000 Btu, or 36 kWh of energy.

2. Read your meter.

The main problem with electricity bills is that you get only one per month! But the power company determines your billed usage by reading your meter, and you can read it yourself just as easily, as often as you like. (The exception would be if you live in a multi-unit building in which the electricity isn’t metered separately for each unit. In that case you’ll have to go on to method 3.)

Reading the old dial-style meters used to be a bit tricky, but nowadays nearly everyone has a digital meter with a simple numerical readout:


The number on the display, 24362 in this case, is the number of kWh of electricity used since some time far in the past—probably whenever the meter was first installed. (The number may blink off and back on every few seconds, in which case you may need to wait a moment to see it.)

So all you need to do is write down the number from the meter (and the time when you read it), then read it again an hour or a day or a week later, and subtract the two values to get the electrical energy usage during that time period. It’s a great exercise to read your meter once a day for a few weeks or months, and to keep a log of the readings, like this:


From this kind of data you can get a very good idea of what kinds of activity use the most electricity: When did you run your air conditioner? When did you do laundry? How much energy does your house use on days when nobody is home?

3. Multiply power by time.

Some electrical devices always use energy at the same rate, whenever they’re turned on. The most familiar example is an ordinary (non-dimmable) light bulb. The rate of energy use is what scientists call power, and we measure it in units of watts. Old incandescent light bulbs commonly used 60 or 100 watts, but modern LED bulbs put out just as much light while using only 10 or 15 watts.

To determine the amount of energy used by a device, you multiply its rate of energy use (that is, the power, in watts) by the amount of time that it’s on:
Energy = Power × Time.
If we measure the power in watts and the time in hours, then we get the energy in units of watt-hours. A kilowatt-hour is 1000 watt-hours, so we divide by 1000 to get the energy in kWh. For example, the energy consumed by a 10-watt bulb left on for 24 hours would be
Energy = (10 watts)(24 hours) = 240 watt-hours = 0.24 kWh,
where I divided by 1000 in the last step. You can similarly estimate the energy use of a 40-watt ceiling fan running for six hours, or of a 1500-watt hairdryer that’s turned on for 10 minutes. Look for power consumption ratings printed on the backs of appliances, or in the owner’s manuals or on the manufacturers’ web sites. Or consult an online list of typical power consumption values. The only catch is that many appliances use less than their nominal power rating under most conditions, or they cycle on and off automatically so that it’s hard to measure exactly how long they’re actually on.

4. Get a plug-in appliance meter.

For a mere $20 or so, you can buy a Kill A Watt P4400 meter, which makes it easy to measure the energy use of any plug-in 120-volt appliance. Use it for a few days to track down unnecessary energy use, and it can easily repay your investment many times over. (There are a number of competing products on the market, but the Kill A Watt is the most common, and is very affordable, so that’s the one I’ll describe. I’ve never seen one in a store, but you can purchase it through many online retailers.)

To use the Kill A Watt meter you simply plug it into a wall outlet (through an extention cord if necessary), then plug your appliance into the meter.  Initially it just displays the line voltage (120 or so), but if you press the rightmost button once, it will display the total energy used since you plugged it in, in kWh. Press the same button again and it displays the time since you plugged it in, so you don’t even need to write that down.

You’ll definitely want to use the meter to test your refrigerator(s), preferably for a day or longer. Other good candidates for testing include televisions, computers, washing machines, and electric blankets.

For some devices you may also want to try pressing the meter’s middle button. Then the display will show the instantaneous rate of energy use (power), in watts or kilowatts. This number will probably fluctuate, especially for something like a refrigerator that periodically cycles on and off. But if the power is reasonably steady and you already know how long the device will be in use, then a quick power reading can save you from having to wait for the energy measurement to build up. Just multiply the power by the time, as described above in method 3.

Don’t forget to test low-power devices that are on all the time, such as clocks and WiFi routers and televisions that never go completely off.

5. Time the little blinking squares.

The main drawback of a plug-in meter is that you can’t use it to measure hard-wired devices or 240-volt appliances. For these, and for those times when you’re caught without a plug-in meter within reach, you can go back out to the power company’s meter, equipped with a stopwatch (probably the one on your smartphone).

This time, instead of looking at the numbers on the display, you want to watch the little blinking squares at the bottom. They should go on and off following a six-step pattern:


(The pattern is meant to mimic the horizontal rotating disk in an old mechanical meter, as if half the disk’s edge is dark and the other half is light, with the front turning from left to right.) Each change in the pattern—a square going on or off—indicates one watt-hour of energy usage. Use your stopwatch to time how long it takes between one change and the next. Or, if the pattern is changing quickly, measure the time for the entire six-step cycle and divide by six. Either way, you can now calculate the power being used in your home as follows:
Power in watts = 3600 / (measured time in seconds).
Explanation: The energy used during your measured time interval was one watt-hour, or 3600 watt-seconds (since an hour is 3600 seconds). But energy = power × time, so to calculate the power, you divide the energy by the measured time.

You’ve now measured the rate at which all the electrical devices in your home are using energy at a particular moment. The trick, then, is to make this measurement with everything except the device(s) you care about turned off. Try it once with all the major appliances turned off, and the refrigerator unplugged or turned off at the breaker panel, to get a power value for all the little stuff in the home that’s using a small amount of power 24 hours a day. Then turn on a major appliance like the furnace or air conditioner or electric dryer, and make another measurement.

Once you know the power of some device of interest, calculate its total energy use by multiplying by how long it’s on, as in method 3.

6. Install a fancy monitoring system.

The five simple methods described above are more than enough to give you the big picture of your home electricity use, including the information you need to save a lot of money (and help save the planet). But if you want to understand every detail of what’s going on in your home, and you’ve exhausted what you can reasonably learn from the first five methods, then the next step is to install a home energy monitoring system. These systems start at about $150, and the installation process is nontrivial.

Electricity monitoring systems are available in several varieties, from several vendors. I have the Efergy Engage Elite Hub System (recommended by Mr. Money Mustache), which is one of the most affordable and easy to use. But I wish I had spent a little more for Efergy’s True Power Meter, which would be more accurate.

The main components of these systems are a pair of clamp-around sensors that you install on the main feed wires coming into your breaker panel. To install them you need to turn off the electricity (otherwise you may die!), open up the panel, and then hope that there’s enough room to fit the clamps around the stiff wires. (I had a tough time with one of them, but finally managed.) If you have any doubts about your ability to do this installation safely, you should hire an electrician.


For a true power meter there would also be a wire to make an electrical connection inside the panel. Either way, the Efergy sensors connect to a transmitter just outside the panel, which beams the data wirelessly to one or two receivers. The data is simply an instantaneous power measurement for your whole house (or at least as much as is powered by this particular panel), equivalent to what you measured in method 5 above. But the monitoring system makes these measurements continually, day and night, with no need for you to use a stopwatch or a calculator.


One type of Efergy receiver contains a digital display for immediate readout, updating every ten seconds. This can sometimes be handy, but in my opinion it’s not worth the price or the installation effort by itself. The other type of receiver, though, is a “hub” that uploads the data over your internet router to Efergy’s web site, where you can look up (and even download) minute-by-minute power levels at any later time, from any location, through your web browser. It’s a data junkie’s dream. Here’s a sample of my own data as viewed on the Efergy web site, showing a steady base load, the refrigerator and furnace cycling on and off, and a big spike from cooking breakfast on my electric stovetop:


As I mentioned above, my basic Efergy sensor isn’t always accurate. Specifically, it’s accurate for “resistive loads” like the stove and other heating appliances, but it reads too high a value for anything with a motor in it, like a furnace blower or a washing machine. The reason has to do with the intricacies of alternating current, and the best solution would be to use a slightly more sophisticated system such as the Efergy True Power Meter or The Energy Detective (a competing product that costs a bit more). The power company’s meter also makes accurate measurements, as does a Kill A Watt meter, so I’ve simply used those to calibrate my interpretation of the Efergy data.

Saturday, April 15, 2017

Qubits or Wave Mechanics?

A few days ago Sean Carroll tweeted a poll:

As someone who’s been wrestling with this question for 30 years, I perked up at this tweet, and not only voted but even tweeted a couple of responses. It’s a fascinating question! 

The second answer is the traditional one, and there are many good arguments for it: a solid experimental basis in phenomena that are easy to demonstrate; vivid images of wavefunctions for building intuition from classical waves; and a huge array of practical applications to atomic physics, chemistry, and materials science. The down-side is that the mathematics of partial differential equations and infinite-dimensional function spaces is pretty formidable. Mastering all this math takes up a lot of time and tends to obscure the logical structure of the subject. Especially if your main interest is in the new field of quantum information science, this is a long and indirect road to take.

Hence the alternative of starting with two-state systems, which are mathematically simpler, logically clearer, and directly applicable to quantum information science. The difficulty here is the high level of abstraction, with an almost complete lack of familiar-looking pictures and, inevitably, no direct connection to most of the traditional quantum phenomena or applications.


A fundamental challenge with teaching quantum mechanics is that it’s like the proverbial Elephant of Indostan, with many dissimilar parts whose connections are difficult for novices to discern. From various angles, quantum mechanics can appear to be about Geiger counters and interference patterns, or differential equations and their boundary conditions, or matrices and their eigenvalues, or abstract symbol-pushing with kets and commutators, or summing over all possible histories, or unitary transformations on entangled qubits. Stepping back to get a view of the whole beast is challenging even for experts, and bewildering for “blind” beginners.

I think most physicists would agree that an undergraduate degree in physics should include some experience with both wave mechanics and two-state systems. Carroll’s Twitter poll, though, asks not what a degree program should include, but how we should introduce physics students to quantum mechanics. That’s a hard question, and one’s answer could easily depend on any number of further assumptions:
  • Who exactly are these “physics students”? Students taking an introductory course, which may be their last course in physics? Typical undergraduate physics majors? Undergraduate physics majors at Caltech? What’s their math background?
  • How long an introduction are we talking about here? A single lecture, or a few weeks, or an entire course?
  • Will this introduction be followed by further study of quantum mechanics? In other words, is the question merely about the order in which we cover topics, or is it also about the totality of what we should teach, and what we can justifiably omit, when we design a course or a curriculum?
  • Are we constrained to use existing resources, including textbooks, instructor expertise, and locally available lab equipment? Or are we dreaming about an ideal world in which any resources we might want are magically provided?
Due to all these ambiguities, we should interpret the poll results with caution. Carroll’s interpretation was that the winning second option “probably benefits from familiarity bias. I’ll call it a tie”—so I infer that his own preference is to start with two-state systems. I agree that some respondents were probably biased in favor of what’s familiar, but I also suspect that Carroll’s Twitter followers have more interest in fundamental theory, and less interest in atoms and molecules, than would a random sampling of physicists.  I also wonder if some respondents weren’t biased in favor of what’s unfamiliar: it’s easy to suggest a radical curricular change if you’ve never actually tried it out and had to live with the unintended consequences. Carroll himself is currently teaching an advanced quantum course that emphasizes two-state systems, but as far as I can tell he has never taught a first course in quantum mechanics for undergraduates.

No professional quantum mechanics teacher should be completely unfamiliar with the two-state-systems-first approach, because it’s used, more or less, in Volume III of the Feynman Lectures on Physics, published in 1965 (thirty years before Schumacher and Wootters coined the term qubit!). I say “more or less” because Feynman actually starts with two-slit interference and other wave phenomena, and then he introduces a three-state system (spin 1) before settling into a lengthy treatment of spin 1/2 and other two-state systems.

There are also some well-known graduate-level texts that begin with two-state systems:  Baym’s Lectures on Quantum Mechanics (1969) and Sakurai’s Modern Quantum Mechanics (1985).

At the upper-division undergraduate level, the earliest text I know of that takes the two-state-systems-first approach is Townsend, which first appeared in 1992. Several others have appeared more recently: Le Bellac (2006), Schumacher and Westmoreland (2010), Beck (2012), and McIntyre (2012). Instructors who want to take this approach in such a course can no longer complain about the lack of suitable textbooks.

But at the lower-division level, where most students first encounter quantum mechanics, the pickings are still slim. Nobody actually teaches out of the Feynman Lectures. You could try to use a few chapters out of one of the more advanced books (McIntyre would probably work best), or you could use Styer’s slim text The Strange World of Quantum Mechanics (2000, written for a course for non-science majors), or you could use the new (2017) edition of Moore’s introductory Six Ideas textbook (which inserts three short chapters on spin and “quantum weirdness” in between electron interference and wavefunctions), or you could try Susskind and Friedman’s Theoretical Minimum paperback (2014, an insightful tour of the formalism with little mention of applications—see Styer’s review here).

I suspect that the time is ripe for someone to write an otherwise-conventional sophomore-level “modern physics” textbook that introduces quantum mechanics via two-state systems and qubits before moving on to wave mechanics. I really wish Moore would expand his Units R and Q into a more complete “modern physics” text!

Personally, I’ve had a soft spot for spin ever since I took a quantum class from Tom Moore in 1982, at the end of my sophomore year (after a conventional “modern physics” class) at Carleton College. This half-term class was mostly based on Gillespie’s marvelous little book, which lays out the logic of quantum mechanics for a single spinless particle in one dimension. But Moore departed from the book to introduce us to two-state and three-state spin systems as well, even writing a simple computer simulation of successive spin measurements for us to use in a homework exercise. The following year I saw more spin-1/2 quantum mechanics in the philosophy of science course that I took from David Sipfle, using notes prepared by Mike Casper, probably inspired by the Feynman Lectures. So when I took Casper’s senior-level quantum course after another year, I was well prepared.

A few years later, while procrastinating on my thesis work during graduate school, I converted and expanded Moore’s computer simulation into a graphics-based Macintosh program. Moore and I published a paper about this program, and how to use it at various levels, in 1993. From there the concept made its way into Moore’s Six Ideas course, and also into the Oregon State Paradigms curriculum and McIntyre’s book. Last year I ported the program to a modern web app.

I recount this history mainly to establish my credentials as an experienced advocate for, and contributor to, the teaching of quantum mechanics via two-state (and three-state) spin systems. So you may be surprised to know that on Carroll’s quiz I actually voted against this approach and in favor of starting with the traditional wave mechanics. And in my own teaching I’ve actually never started with spin systems: I’ve always started with one-dimensional wave mechanics in both upper-division quantum mechanics and sophomore-level modern physics. In calculus-based introductory physics I teach a little about wave mechanics and don’t really cover two-state systems at all. My reasoning is simply that for these students, in these courses, the balance of the pros and cons listed above seems to weigh in favor of starting with wave mechanics.

Meanwhile, I think there are opportunities to improve on the way we teach wave mechanics. One serious drawback with most wave mechanics text materials is their relative neglect of systems of more than one particle. As a result, students tend to develop some misconceptions about multiparticle systems, and don’t hear about entangled states—an important and trendy topic—as early as they could. I’ve recently written a paper on how to address this deficiency, with some accompanying software to help students visualize entangled wavefunctions.

My bottom-line opinion, though, is that the best answer to Carroll’s question depends on both the students’ needs and the instructor’s inclinations. Back in 1989, Bob Romer published an editorial in the American Journal of Physics titled “Spin-1/2 quantum mechanics?—Not in my introductory course!” But he hastened to clarify: “not in my course, thank you, but maybe in yours”—enthusiastically encouraging instructors to innovate and to follow whatever teaching plan they believe in. I wholeheartedly agree.

Sunday, August 28, 2016

The Ecobee Smart Thermostat: A Data Junkie’s Dream

In an attempt to reduce my heating bills and carbon footprint, last September I installed an Ecobee 3 smart thermostat.

Now, after using it through a full heating season and analyzing the results, I can report that it accomplished everything I hoped.

Should you buy one too? That depends.

Why the Ecobee?

The idea behind a “smart” thermostat is to gather a whole bunch of data (past temperatures and settings, furnace and AC run times, outdoor weather, and times when you’re home and awake), then use this data to anticipate your heating and cooling needs and to keep you comfortable, automatically, without wasting energy. If you want a thermostat that does this then you can consult any number of online reviews for advice.

I don’t want my thermostat to set itself automatically. I’m fully capable of setting it myself, thank you very much, and I stubbornly cling to the notion that I’m still smarter than any thermostat.

But I decided to get a smart thermostat anyway, because I wanted the ability to remotely monitor the temperature in my house over the internet, and to remotely adjust the setting from time to time. Also, I wanted to get my hands on all that data. As usual, I take my mantra from Mr. Money Mustache: Measure everything, then get angry at waste!

The most popular smart thermostat is the Nest, but for my purpose it has a fatal flaw: They don’t let you download the data! You can view some daily summary data over the internet, and they send you monthly summaries by email, but the manufacturer has decided that you’re not even allowed to see the full minute-by-minute temperature and operation data, much less download it.

The Ecobee folks, on the other hand, treat their customers with respect. Through their web interface you can view a detailed chart of what’s happening in your house, and with a few clicks you can download the data as a CSV file for analysis in a spreadsheet or other software.

That feature was enough to earn my business, so I went ahead and ordered an Ecobee, directly from the manufacturer. The price was $249, but I got a $100 rebate from my gas company. Installation was easy, although there can be complications depending on how your existing system is wired. With a couple of taps on the touch screen I configured it for fully manual operation.

My house has no air conditioning, so during the summer I use the Ecobee only as a remote-monitoring and data-logging device. It does, of course, use some electricity to accomplish these things: about 7 watts of continuous power, which adds up to 60 kilowatt-hours (about $6 worth here in Utah) of electrical energy per year. It also requires a continuously operating internet connection and wifi router.

One unique feature of the Ecobee 3 is that it comes with a wireless, battery-powered external sensor that you can use to monitor the temperature in another room, away from the thermostat. Their advertising suggests that this is almost as good as being able to heat different parts of your house independently, but of course that’s not the case; you merely have the flexibility to control the heat based on the temperature at one or another location. I put the external sensor in my basement laundry room, so I could make sure the pipes wouldn’t freeze when I was away during the winter. (Being a data junkie, I eventually purchased two more external sensors, for another $79, so I could also monitor the temperature in my living room and bedroom.)

How I cut my gas use by 35% [see update below]

As it turned out, that external sensor in the basement is what saved me the most money. I was away from home quite a bit during the winter of 2015-16, and at those times I aggressively set the thermostat down, letting the temperature drop to 48 F upstairs and 40 F in the basement. Without the sensor next to the water pipes, and the ability to remotely monitor it and make adjustments if needed, I never would have taken the risk of turning the thermostat so low.

To put my savings in perspective, here’s a plot of my annual natural gas use ever since I bought my house in 1998:


The total for 2015-16 was 18.4 decatherms (MBtu), or 35% less than my average use from 2004 through 2015. When you consider that some of that (about 4 decatherms, I think) is for my hot water heater, the reduction is even more impressive. Gas is cheap here in Utah—about $8 per decatherm—so I saved only about $80 over the season, and it’ll take another year before the thermostat nominally pays for itself. On the other hand, not all of the reduction was a direct effect of the smart thermostat: my motivation to save energy was probably at an all-time high, and it’s possible that the winter was a little warmer than average [see update below].

Getting the detailed data

And what about the detailed thermostat data? Here, to start with, is a screen capture showing what you can view through the Ecobee web interface:


The orange graph is the thermostat setting; the white graph is the temperature at the thermostat; the green graph is the outdoor temperature (obtained from public weather data for my local area, so it’s not literally the temperature right outside my house); and the orange bands at the top show when the furnace was running. On this particular day I kept the thermostat at 64 degrees when I was home, but set it down to 58 when I was at work. The furnace cycled on and off seven times between midnight and 8 am, didn’t run at all while I was away, ran for more than a half hour to warm the house up when I returned, and then cycled on and off four more times before midnight.

This web interface to the data is a wonderful thing, but I find it a little clunky and hope they’ll make some improvements in the future. Although you can scroll through the entire time period since your thermostat was installed, you can’t zoom out to view more than 24 hours of data at a time. Updating the graph with new incoming data requires multiple clicks and a delay of about 10 seconds. The graph always omits the most recent hour or so, and it won’t show the separate data from all your sensors, even though you can view all the current readings on a different web page.

To get a more comprehensive picture you need to download the data and plot it up yourself. Fortunately, the download process is easy and fast. As I mentioned above, you get a CSV file that you can open in a spreadsheet. The file contains a row for every five-minute time interval, and each row contains 20 or more data fields: date, time, thermostat settings, heating/AC/fan activity, outdoor temperature and wind speed, and, for the thermostat itself and each external sensor, the temperature and whether the motion detector was activated. You can download up to a month’s worth of data (more than 8000 rows) at a time.

The ways of plotting up all this data are endless. Here, for example, is a plot of my temperature data for the month of July. Can you guess which week I was out of town?



Thermal properties of my house

One of my goals in obtaining all this data was to measure the thermal properties of my house. To do this I focused on the six-month heating season from November through April, and selected eight-hour-long periods at night (to avoid solar heating) when either the furnace was holding the indoor temperature steady, or the furnace didn’t run at all. (I didn’t use data from nights when neither of these conditions was met for eight consecutive hours.)

Working with the steady-temperature data, I used the furnace running time to calculate the rate at which the furnace had to supply heat to the house, to maintain the steady temperature. To calculate the heat rate I had to know that the furnace is rated to use 75,000 Btu per hour, at an efficiency of 92%; I’ve checked the Btu/hr value by reading my gas meter, but I have no good way to check the efficiency. Here is a plot showing the heating rate as a function of the average temperature difference between inside and outside:


You can immediately see from this plot that my 75,000 Btu/hr furnace (69,000 Btu/hr when you factor in the 92% efficiency) is much more powerful than necessary. Even on the coldest nights it needed to put out only about 14,000 Btu/hr to maintain a steady indoor temperature, so it was running only about one fifth of the time. Extrapolating, I conclude that my furnace could maintain a steady indoor temperature even if the outdoor temperature were as much as 200 degrees lower than indoors! How’s that for over-engineering?

A linear fit to the plotted data gives a slope of approximately 344 Btu per hour per degree Fahrenheit, meaning that for each additional degree in the temperature difference, the furnace had to supply additional heat at a rate of 344 Btu/hr. Of course that heat must also be escaping from the house (through the walls, windows, ceiling, and foundation) at the same rate, because the indoor temperature wasn’t changing. The value 344 Btu/hr/°F is therefore what is called the thermal conductance of the exterior envelope of my house.

There’s quite a bit of scatter in the data, so this measured conductance is somewhat uncertain. The standard error in the best-fit slope is only 6.4%, but when I plot subsets of the data (chosen by time of year or thermostat setting) I get a much wider range of values, so I would put the uncertainty very roughly at 20%.

You can also see from the plot that a best-fit line does not go through the origin; in fact the vertical intercept is at −2800 Btu/hr, with a rather large uncertainty (perhaps 40%). This means that on a typical winter night, heat from some other source must be entering my house at a rate of roughly 2800 Btu/hr, or about 800 watts. Some of that is from the refrigerator, electric blanket, and human bodies, but after slicing and dicing the data I’m convinced that there’s also a contribution from underground heat coming in through the basement floor and foundation.

In principle, you can calculate the thermal conductance of a house without making any temperature measurements at all. You just need to know the sizes and thermal conductivities (R values) of the components of the exterior envelope. Add the R values for each layer of a given component (e.g., plaster, wood, brick, and air films for my uninsulated walls), then divide this total R value into the surface area to get that component’s contribution to the conductance. I had never before done this calculation for my house, because there’s a lot of guess-work involved and I had no good way to check the answer. But now I have done the calculation, and amazingly, I obtained a total conductance of 374 Btu/hr/°F, within ten percent of the measured value! The pie chart shows a breakdown of how each major component of my house’s envelope contributes to this calculated total.

The ceiling contribution is small because it’s the only place where my 81-year-old house has at least a little bit of insulation. Of course, these fractional contributions could still be pretty inaccurate. But I now have enough confidence in my calculations to start considering whether I should try to add insulation to my exterior walls and foundation.

By the way, people sometimes say that homeowners should focus on air infiltration as a major source of heat loss. That may be true for some homes, but I’ve always been skeptical in my own case. My calculations justify this skepticism because I was able to account for more than 100% of my house’s measured heat loss through conductance estimates alone, completely ignoring infiltration.

Meanwhile, as mentioned above, I’ve also looked at data from winter nights when the furnace didn’t run at all—so the indoor temperature dropped steadily. Here is a plot of the rate of temperature decrease as a function of the average temperature difference between inside and outside:


The slope of this graph is minus the thermal conductance divided by the effective heat capacity of the interior of my house. (So a high thermal conductance makes the graph steeper, because heat escapes faster, while a high heat capacity makes it shallower, because there’s more energy that needs to escape in order for the temperature to drop by a given amount.) The best-fit slope is −0.023 degrees per hour, per degree (or simply inverse hours if you prefer). Dividing this into the previously measured conductance of 344 Btu/hr/°F gives a heat capacity of approximately 15,000 Btu/°F. That’s equivalent to the heat capacity of 15,000 pints of water, or 1800 gallons, or enough to fill my bathtub up to the brim 26 times. So filling the bathtub wouldn’t make much of a dent in the total heat capacity!

An alternative way to estimate the heat capacity is simply to measure how long it takes the furnace to warm the house up after adjusting the thermostat upward. For example, on one winter evening it took my furnace two hours to warm the house by 14 degrees Fahrenheit. The furnace supplied 138,000 Btu of heat over that time, so the estimated heat capacity would be (138,000 Btu)/(14°F) = 10,000 Btu/°F. The effective heat capacity is smaller over this relatively short time period, because less of the house is actually being warmed up by the full amount.

In principle I could try to calculate a theoretical heat capacity, by adding up all the contributions of the materials and contents of my house. It would be interesting to know roughly what percentage comes from wood, plaster, concrete, and so on. But making reasonably accurate estimates would be quite a bit of work, so I’ll put that off to another day.

The more useful thing to know is that even on a very cold night (bottom-right corner of the graph), my house cools down at a rate of less than a degree Fahrenheit per hour. This means that setting the thermostat down for, say, eight hours at a time saves only a small amount of energy, because the average indoor temperature over that time will be no more than two or three degrees lower. This average drop is what matters, because it determines how much less heat the house loses to the outdoors—and therefore how much less heat the furnace must replace. Any further energy savings from not running the furnace during this time will be offset when you run it to heat the house back up afterwards. (You can see all this vividly in the screen-capture image above.)

So how did I save huge amounts of energy, cutting my gas bill by 35%? Partly by setting the thermostat somewhat lower even when I was home, but mostly by setting it way down when I was away for 24 hours at a time or longer. If your house is never unoccupied for more than half a day at a time, then you shouldn’t expect dramatic winter energy savings from a smart thermostat. Summer might be another matter if you use air conditioning, but I wouldn’t know. And if you own a vacation home that’s unoccupied for half the winter, then install a smart thermostat in it immediately!

Update, July 2019

Honesty compels me to report that over the last three years I’ve failed to keep my gas use as low as it was during 2015-16. Here is an updated chart:


Over these last three years my annual gas use has averaged 23.6 decatherms, which is only 16% less (not 35% less!) than the average from 2004 through 2015 (before I installed the Ecobee thermostat). The most recent winter was the coldest of these three, so I’m not too worried about a continuing upward trend in gas use as the chart might suggest. Instead I think I’ve reached a new normal, after the anomalous one-time low during 2015-16.

The direct carbon emissions from burning 23.6 decatherms of natural gas come to 1.25 metric tons (2760 pounds), so this contribution to my personal carbon footprint is somewhat larger than any one of the contributions from electricity use, driving, or flying.

Saturday, December 12, 2015

Textbook Price Pandemonium

Physics textbook prices have gotten crazier than ever. Just look:

Author Subject Publisher List price
SerwayModern physicsCengage$368.95
Thornton and RexModern physicsCengage$355.95
Tipler and LlewellynModern physicsMacmillan$182.99
OhanianModern physicsPearson$179.00
Taylor et al.Modern physicsUniv. Sci. Books   $98.50
Fowles and CassidayMechanicsCengage$404.95
Marion and ThorntonMechanicsCengage$401.95
HamillMechanicsJones & Bartlett$303.95
TaylorMechanicsUniv. Sci. Books$124.50
WangsnessElectrodynamicsWiley$205.95
GriffithsElectrodynamicsPearson$174.60
OhanianElectrodynamicsJones & Bartlett$164.95
CookElectrodynamicsDover$34.95
GasiorowiczQuantum mechanics   Wiley$224.95
GriffithsQuantum mechanicsPearson$193.20
McIntyreQuantum mechanicsPearson$135.20
TownsendQuantum mechanicsUniv. Sci. Books$98.50
BeckQuantum mechanicsOxford$89.00
CarterThermal physicsPearson$187.20
Kittel and KroemerThermal physicsMacmillan$154.50
ReifThermal physicsWaveland Press$111.95
BaierleinThermal physicsCambridge$105.00
SchroederThermal physicsPearson$71.60
HechtOpticsPearson$209.40
Pedrotti et al.OpticsPearson$204.40
GuentherOpticsOxford$98.50
Peatross and WareOpticsLulu/self$21.30
FowlesOpticsDover$19.95
Ashcroft and Mermin   Solid stateCengage$398.95
KittelSolid stateWiley$203.95
SnokeSolid statePearson$165.20
MyersSolid stateTaylor & Francis$87.95

Here I’ve tried to list a representative sample of textbooks, including the most popular ones, for seven standard physics courses at the sophomore through senior level. The list prices came from the publishers’ web sites, accessed during November and December 2015. To see a more complete list, click here.

How did the average price of such books climb to nearly $200? And what are we to make of the fact that Cengage now gouges students for $350 to $400 per book, even while other publishers sell competing books for under $100?

Nearly 18 years ago I wrote a web article about physics textbook prices, showing how they generally tracked inflation from 1960 through the early 1980s but then began rising steadily, outpacing inflation by about 50% by 1998. At that time there was much less variation in prices, and the average price for books at this level was about $80. But the cost of living in the U.S. has increased by nearly 50% since then, so in today’s dollars the 1998 average would be about $120. Before 1985 the average price, in today’s dollars, was about $75. So on average, after inflation, these types of textbooks now cost about two and a half times what they did 30 (or 50) years ago. 

I won’t repeat every explanation I offered in that earlier article, or in a more recent post on this blog, but the most important factor behind high textbook prices hasn’t changed: The people buying the books (students) aren’t the same as the people choosing the books (professors). This system effectively eliminates most of the price competition you would otherwise expect.

A secondary factor, though, has been the bewildering series of mergers, acquisitions, spin-offs, and rebrandings of the major commercial textbook publishers. Addison-Wesley and Prentice Hall are now Pearson; Freeman is now Macmillan; Saunders, Harcourt Brace, Brooks Cole, and others are now Cengage. And the bigger a publishing company gets, the more separated the corporate decision makers become from the people who are affected by their decisions.

Meanwhile, the major commercial publishers are devoting more and more resources to frequent revisions of mass-market introductory textbooks and, especially, to the online homework and tutorial systems that accompany these textbooks. Their ultimate goal seems to be to take over the teaching of these courses entirely, making faculty superfluous.

But software development is expensive, so such a program is out of the question for courses that enroll under ten thousand students a year nationwide. Publishing textbooks for these smaller markets is really no different from the way it was 30 years ago, but when it happens inside a huge company whose main business is mass-market course materials, the small-market books seem to be taxed to pay for all the overhead.

Physics textbooks beyond the introductory level have become a mere afterthought for most of the big commercial publishers, and have been completely abandoned by others. McGraw-Hill, once a major publisher of advanced physics textbooks, got out of that business 10 or 15 years ago. Pearson sold the Addison-Wesley Advanced Book Program to Perseus/Westview in the late 1990s, but has remained the dominant publisher of undergraduate and beginning graduate texts; yet despite this success, it is now telling authors that it will no longer publish any new upper-division physics titles. Wiley, as far as I can tell, is the only big commercial publisher that is still whole-heartedly in the upper-division (and beyond) physics textbook business.

On the other hand, more and more undergraduate textbooks are now being published by the Cambridge, Oxford, and Princeton university presses, and by small publishers like University Science Books. These publishers demonstrate that high-quality textbooks for small-market courses can still be published at about the same (inflation-adjusted) prices as during the 1960s, 70s, and early 80s.

At still lower prices, Dover has reprinted a few classic undergraduate physics textbooks, to add to its much more extensive collection of classic graduate-level textbooks. And a small but growing number of high-quality textbooks are now being self-published through services like CreateSpace and Lulu.

Of course it must be pointed out that fewer and fewer students are paying the full list prices for their textbooks. Online retailers typically sell new textbooks at discounts of around 20%, and it’s easier than ever to buy used textbooks at deeper discounts. The lowest prices of all are on international editions that are intended for sale in Asia but, thanks to a 2013 Supreme Court decision, legally available in the U.S. Traditionally these editions have been inferior in their print and paper quality, and now Pearson, at least, is also abridging their content to deliberately lower their value.

Let me end with a few notes regarding some particular books in the list above. Modern Physics by Taylor, Zafiratos, and Dubson was published by Prentice Hall and then Pearson until 2013, when Pearson took it out of print and the authors took it to University Science Books—resulting in a significantly lower price. Similarly, Reif’s Fundamentals of Statistical and Thermal Physics was formerly published by McGraw-Hill but has now found a new lower-overhead home at Waveland Press. Snoke’s Solid State Physics apparently went out of print around the time I was writing this article, because it was available from Pearson when I compiled the list but isn’t any more. The self-published optics textbook by Peatross and Ware, available in hard copy through Lulu, can also be downloaded for free from the authors’ web site. And my own book, An Introduction to Thermal Physics, costs much less than Pearson’s other textbooks because I did all the typesetting, artwork, and layout myself, and insisted on a clause in our contract to limit the book’s price. I’m now more glad than ever that I did it that way.

Update, 2 January 2016: Here’s a plot of all the price data in my spreadsheet, grouped by publisher. This plot not only highlights what an outlier Cengage is, but also shows that there are only four other publishers with multiple books priced above $150. However, this handful of publishers produces some of the most widely used textbooks.


Wednesday, April 16, 2014

Fuel Economy vs. Power

The recent experience of buying a new car left me angry and bewildered over the meager choices for those of us who care about fuel economy. Here we are in 2014, more than 40 years after the OAPEC oil embargo, and in the U.S. you still can’t buy a liquid-fueled car with an EPA combined rating above 50 miles per gallon. Only a handful of cars exceed 40 mpg, and your selection is pretty limited until you get down to mpg ratings in the low 30s. The most efficient pickups and minivans get 23 and 24 mpg, respectively. (Throughout this article I’m using city/highway “combined” fuel economy values under the current, less generous, EPA rating system.)

To some extent the limitations on fuel economy are due to basic physics: air and rolling resistance, braking losses, and thermodynamic limits on engine efficiency. But the existence of the 50 mpg Prius and of high-efficiency cars sold outside the U.S., not to mention the 47 mpg Geo Metro from a generation ago, raises the question of why more cars aren’t comparably efficient. The short answer is that most American car buyers don’t care. Or rather, they care much more about other factors such as size, price, appearance, and power. The most interesting of these is power.

Each year the EPA publishes a report under the cumbersome title Light-Duty Automotive Technology, Carbon Dioxide Emissions, and Fuel Economy Trends. All 135 pages of the latest Trends report are informative, but I’ll highlight just Figure 2.3, which shows some trends in fleet-wide averages for new vehicles sold in the U.S.:


First look at the line for weight, which decreased sharply by 20% in the late 1970s (as more people bought small cars), then began creeping upward in the late 1980s (as SUVs became popular). By 2004 the average vehicle weight was back to its 1975 value, and it has stayed there since.

Simple physics predicts that fuel economy should increase by about the same percentage that weight decreases, all other things being equal. But all other things have not been equal. Since 1975 we’ve seen steady improvements in engine and drive train efficiency, as well as in aerodynamics. Today’s new vehicles are 80% more efficient than in 1975, with essentially no change in average weight.

My point, though, is that the efficiency gain could have been significantly more than 80%, even with the same weights and the same technologies. Look at the trend in horsepower, which has been rising much faster than weight for the last 30 years. A higher power/weight ratio translates into faster acceleration, but (other factors being equal) lower fuel economy. Let’s quantify these effects.

A thorough statistical analysis of the acceleration performance of U.S. vehicles was published a couple of years ago (in both report and poster formats) by MacKenzie and Heywood of MIT. Their data set of 1500 cars and light trucks came from tests done by Consumer Reports, and was representative of the U.S. auto fleet as a whole. The results are striking:


Whether you look at the median (black curve), the slowest vehicles (red curve), or the fastest vehicles (green curve), 0-60 mph acceleration times are barely over half what they were in the early 1980s. To quote from MacKenzie and Heywood, “Acceleration performance that was typical in the early 1990s would put a vehicle among the slowest on offer today. Even the slowest end of the market (95th percentile) today delivers performance that was reserved for the fastest vehicles (5th percentile) in the mid-1980s.” Some of this increased performance has come from improvements in drive trains and aerodynamics, but most of it is a direct result of higher power/weight ratios. MacKenzie and Heywood found that with other factors held fixed, each 1% increase in power reduces the 0-60 mph acceleration time by about 0.7% for lower-power vehicles and about 0.58% for higher-power vehicles. (I think these values are less than 1% because limited traction prevents a vehicle from using its full power at low speeds.)

But why should engine power affect fuel economy? The answer lies not so much in basic physics as in the practicalities of engine operation. My amateur’s understanding is that running a gasoline engine at less than its full power means filling the cylinders at less than atmospheric pressure. You then get less force during the power stroke, with a proportional reduction in fuel consumption, while there’s no reduction in the friction between the piston and the cylinder wall—and that friction lessens the efficiency. In other words, a smaller engine running closer to full throttle is more efficient than a larger engine that’s being throttled back to produce the same power output.

So much for qualitative understanding. What about some numbers? 

I couldn’t easily find a quantitative analysis of the effect of engine power on fuel economy, so I did a quick empirical analysis of my own. Lacking the time to study every vehicle on the U.S. market, I started with a list of the 30 best-selling models in 2013. I then looked up each of these models in the 2014 EPA database, and picked out those that come with more than one engine option. I further pruned the list down to pairs of vehicles with different engines but the same (or nearly the same) transmission and drive type, and I eliminated duplicate pairs (e.g., same two engine options with different drive trains, or similar vehicles sold under different names). I also eliminated vehicles with turbocharged engines, which are generally more efficient but add a lot of noise to the data. Finally I was left with 14 vehicle pairs (5 cars, 3 SUVs, and 6 pickups) to compare, and I looked up the engine power for each on the manufacturers’ web sites. Here’s the final list:

Vehicle (transmission)   Engine 1   HP   MPG     Engine 2   HP   MPG     ΔHP   ΔMPG
Chevrolet Impala (auto 6) 2.5L 4cyl 195 24.5 3.6L 6cyl 305 21.4 56% −13%
Honda Accord (manual 6) 2.4L 4cyl 185 27.7 3.5L 6cyl 278 21.6 50% −22%
Hyundai Elantra (auto 6) 1.8L 4cyl 145 31.5 2.0L 4cyl 173 27.9 19% −11%
Nissan Altima (auto CVT) 2.5L 4cyl 182 31.2 3.5L 6cyl 270 25.3 48% −19%
Toyota Camry (auto 6) 2.5L 4cyl 178 28.7 3.5L 6cyl 268 24.8 51% −14%
Chevrolet Equinox AWD (auto 6) 2.4L 4cyl 182 23.5 3.6L 6cyl 301 18.9 65% −19%
Jeep Grand Cherokee 4WD (auto 8)    3.6L 6cyl 290 19.5 5.7L 8cyl 360 15.9 24% −18%
Jeep Grand Cherokee 4WD (auto 8) 5.7L 8cyl 360 15.9 6.4L 8cyl 470 14.9 31% −7%
Chevrolet Silverado 2WD (auto 6) 4.3L 6cyl 285 19.8 5.3L 8cyl 355 18.6 25% −6%
Chevrolet Silverado 2WD (auto 6) 5.3L 8cyl 355 18.6 6.2L 8cyl 420 17.0 18% −9%
Ford F150 4WD (auto 6) 3.7L 6cyl 302 17.5 5.0L 8cyl 360 15.9 19% −9%
Ford F150 4WD (auto 6) 5.0L 8cyl 360 15.9 6.2L 8cyl 411 13.4 14% −16%
Ram 1500 2WD (auto 8) 3.6L 6cyl 305 19.7 5.7L 8cyl 395 17.3 30% −12%
Toyota Tacoma 4WD (manual 5/6) 2.7L 4cyl 159 19.2 4.0L 6cyl 236 17.0 48% −11%

The last two columns show the differences in power and fuel economy, respectively, between the first and second engine options. Here’s a plot of these two columns, showing that there’s quite a bit of scatter in the data but the decreasing trend is clear:


On average, the percentage decrease in fuel economy is about 1/3 of the percentage increase in engine power. So, for example, a 30% increase in power typically results in a 10% decrease in fuel economy.

On one hand, these results help explain why consumers are so inclined to choose power over fuel economy: In percentage terms, you typically get about three times the added power for every bit of fuel economy you’re willing to sacrifice! On the other hand, MacKenzie and Heywood’s analysis shows that your 0-60 mph acceleration time drops by only about 2/3 as much as the power gain (in percentage terms), or about twice the percentage that the fuel economy drops. And of course, bigger engines are also more expensive. Given that Americans were happy to buy much less powerful vehicles only a generation ago, it’s hard to believe that most consumers are behaving rationally when they choose more powerful vehicles.

(In some places you’ll read that cars with slower acceleration are less safe—though I’ve never seen any actual evidence for this claim. Leaving aside the likelihood that powerful cars encourage stupid people to drive stupidly, I suppose the argument is that you need fast acceleration to safely merge onto a freeway where traffic is moving rapidly. Yet somehow we still share freeways with heavy trucks and buses and RVs and vehicles towing trailers and quite a few 25-year-old economy cars, all with accelerations much slower than that of any of today’s light-duty vehicles. In practice, slow acceleration just means you sometimes need to wait a little longer before it’s safe to merge. It’s really a question of incremental convenience, not safety.)

Hypothetically, if Americans were willing to go back to the acceleration performance of vehicles made in 1985, we could immediately increase the average fuel economy of new cars by more than 30%. Realistically, that’s not going to happen unless there’s another oil crisis or similar shock to the economy. The most we can probably hope for is that acceleration performance (and vehicle weight) will plateau, so future technological improvements will translate fully into better fuel economy.

Meanwhile, I wish the auto makers would offer just a few more extra-efficient vehicles of various designs, to give consumers more choice. By combining power levels that were typical of the early 1990s with the best current technologies for engines, transmissions, hybrid systems, and aerodynamics, it shouldn’t be hard to produce a 40 mpg small SUV, a 35 mpg minivan, a 30 mpg pickup, and a 60 mpg subcompact. They might not become the instant market leaders, but they would still get plenty of attention, sell to the niche market of sane consumers, and perhaps raise everyone’s expectations for the future.

Saturday, October 19, 2013

Inventory of Physics Simulations in HTML5/JavaScript

When I discovered last winter how useful JavaScript and the HTML5 canvas element can be for physics simulations, I was astonished that there seemed to be so few examples of such simulations out there. That situation is rapidly changing. Here’s an inventory of the examples I’m aware of at this time.

My own portfolio of three simulations is unchanged, except for a few bells and whistles added to each of them:
Over the summer, with support from the Weber State University Beishline Fellowship, our student Nathaniel Klemm ported five of the simulations that my colleague Farhang Amiri uses in his general education physics course:
(The original versions of these simulations were written by Farhang Amiri and Brad Carroll in Adobe Director, and runnable through the Shockwave browser plugin. These were part of a much larger collection of simulations that they developed in the 1990s. Unfortunately, support for the Shockwave plugin is becoming problematic.)

Andrew Duffy of Boston University has created some simple mechanics simulations:
These would be good examples for a beginning HTML5 developer to learn from, since their code is short and straightforward. (Andrew and I will be giving a workshop on beginning HTML5 simulation development at the 2014 AAPT summer meeting next July.)

Dan Cross of Haverford College has created two extremely elegant simulations that I especially recommend:
John Denker has a simulation that draws hydrogen wavefunction scatter plots:
Dan Styer and Noah Morris of Oberlin College have created a nice demonstration of two-slit interference:
This simulation uses the jQuery UI library for its slider controls, which unfortunately makes them unusable on devices that rely on touch events.

GlowScript is a 3D graphics library built on WebGL, created by David Scherer and Bruce Sherwood who modeled it on their earlier VPython system. GlowScript is accompanied by a web-based development environment that eliminates the need to write HTML, although it can also be used as an ordinary JavaScript library. Some collections of GlowScript examples are posted here:
Unfortunately, the use of WebGL makes GlowScript simulations runnable only under certain browsers. As of this writing they will not run on most mobile devices, although some mobile devices offer partial support.

Francisco Esqembre of the University of Murcia has created a high-end development environment for quickly creating physics simulations, called Easy Java Simulations. Although EJS is a Java program, the new version 5 beta release can output stand-alone HTML5/JavaScript code. More than a dozen examples are now posted here:
The PhET group at Colorado has recently gone public with its first six HTML5 simulations for introductory physics and chemistry:
As you would expect from PhET, these simulations are extremely professional and hence the code, which relies on a vast collection of libraries, is unreadable by mortals.

All of the simulations listed above were created by (or under the supervision of) academic physicists, primarily for the purpose of physics education. But of course the vast majority of graphics-intensive HTML5 development is being done by game developers. Here are a couple of these efforts that contain good physics and are fun to play with:
And that’s my list for now. If any readers out there would like to add to this list, feel free to leave links (noncommercial, please) in the comments.

Wednesday, July 24, 2013

Java vs. JavaScript vs. Python


At last week’s AAPT meeting I presented a poster showing how fun and easy it is to do fluid dynamics simulations using current personal computers and software. These simulations are computationally intensive, so every bit of performance counts. On the other hand, students and hobbyists and other nonexperts like myself rarely have time to write code that will squeeze every last drop of performance out of our machines. Also, it’s hard to share code written in C or Fortran—the languages of professionals—with other nonprofessionals.

So in recent years I’ve been writing all my physics simulations in Java or Python or JavaScript. And for my poster presentation I decided to clock these languages against each other. I had already written two-dimensional lattice-Boltzmann fluid simulations in all three languages (code posted here), so all I had to do was run them with the same lattice dimensions and measure the number of calculation steps per second. Here are the benchmark results:


This algorithm performs about a hundred basic arithmetic calculations per lattice site per time step, so the Java version, at over 1000 steps per second for 16,000 lattice sites, is performing well over a billion calculations per second on my 2.3 GHz i7 MacBook Pro. I suspect that C or Fortran would run about twice as fast.

All three versions of this simulation include animated graphics, but I was careful to do the graphics in ways that didn’t significantly slow down the computation. In Java, the graphics automatically runs in a separate thread, presumably on a separate processor core.

Since my laptop has four processor cores, I could have sped up the Java version about threefold by parallelizing most of the computation. But that would violate the spirit of this test, which is to see what can be done without getting too fancy with the code. Perhaps Python can also be configured to make better use of my hardware, but I have no clue how to do so (I’m simply using the EPD Free Python installation). I did use NumPy to vectorize everything in Python, since Python loops are glacially slow.

The JavaScript results are shown for only the two fastest browsers, Chrome (version 27) and Firefox (version 22). It seems that Chrome has gotten slightly faster since my earlier tests in March, while Firefox has sped up significantly since then but still hasn’t caught up to Chrome. Both, in any case, offer remarkably good performance at more than half the speed of Java. Safari (6.0.5) is no faster than the previous version, coincidentally about the same speed as Python/NumPy. Opera (12.16) is still far too slow to bother with for this kind of simulation.

Of course, these three languages serve rather different purposes. JavaScript is for web deployment, while Python is for tinkering around on one’s own workstation. Java is fading away as a web platform, but I still like it for personal use when speed and/or interactivity is important.

Update, December 2017: In the four years since I wrote this article, JavaScript execution speed under all browsers has continued to improve. Some typical values that I obtained recently (on the same 2012-vintage MacBook Pro) were 787 steps per second in Chrome, 875 in Firefox, 770 in Opera, and 399 in Safari. The performance isn’t very consistent from one run to the next, and I’m not sure why. I’m also perplexed by Safari’s poor performance, because it does about as well as the other browsers on other computationally intensive physics simulations. The other three browsers are fast enough that it makes sense to increase the number of calculation steps per animation frame from the default 20 up to 30 or even 40. Then Opera typically runs at about 900 steps per second and Chrome and Firefox are a little faster still, rivaling the performance of Java.