Chronology Current Month Current Thread Current Date
[Year List] [Month List (current year)] [Date Index] [Thread Index] [Thread Prev] [Thread Next] [Date Prev] [Date Next]

[Phys-L] units of measurement -- convenient software approach



Hi Folks --

Here is a small but useful idea. It is standard procedure
in some circles ... but it is not nearly as widely known
as it should be.

When doing calculations in software, it is a good practice,
in most situations, to pick a consistent set of “preferred”
units (such as SI) and use it for all internal calculations.
If some external source feeds you data in some other units,
convert to the chosen internal units as soon as possible on
input. By the same token, convert from the chosen internal
units to external units as late as possible on output.

Here is a good technique for doing this. Consider the following
example:

inch = 0.0254; // [meters] official definition of inch
foot = 12*inch; // official definition of foot

minute = 60; // [seconds]
hour = 60 * minute;
mile = 5280 * foot;
mph = mile / hour; // [m/s]

myspeed = 80*mph;

In this code, the “mph” variable represents one mile per hour
measured in the chosen internal units (in this case SI units).
So, when we write 80*mph, it says what it means and means what
it says: 80 miles per hour.

When converting something for output, you have to think for a
millisecond, at least until you form the habit of doing things
the right way. Here’s an example:

cout << "The speed is " << myspeed/mph << " miles per hour." << endl;
// (A) (B)

where dividing myspeed by mph makes sense in terms of the
factor-label method, especially when you see (A) in the
context of (B) in this example. Also the scaling is correct,
in the sense that if mph is a “big” unit, the number that gets
printed is smaller, since we need fewer such units to do the job.

I don’t like to spend much time discussing misconceptions and
bad ideas, so let me just mention in passing that there are
other ways of handling the unit-conversion task that are an
order of magnitude clumsier and uglier.

Being fastidious about the units is absolutely mandatory. If
you need a reminder of why, consider the Mars probe that was
lost, at a cost of 328 million dollars, due to a mixup in
the units.
http://www.av8n.com/computer/img48/logo-98t-s.png

I wrote up a discussion of this point and put it here:
http://www.av8n.com/computer/htm/good-software.htm#sec-units