UNITS(1)
๐ units(1) โ unit conversion and calculation program ๐
straight outta the General Commands Manual, bestie. buckle up, this one's a whole journey ๐ฆ
โจ NAME โจ
units โ unit conversion and calculation program. that's it, that's the whole vibe.
๐ธ SYNOPSIS ๐ธ
units [from-unit [to-unit]]
units [-hcemnSpqsv1trUVI] [-d digits] [-f units file] [-L logfile]
[-l locale] [-o format] [-u unit system]
[from-unit [to-unit]]
units [--help] [--check] [--check-verbose] [--verbose-check] [--list-
units] [--digits digits] [--exponential] [--file units file]
[--log logfile] [--locale locale] [--minus] [--oldstar]
[--newstar] [--nolists] [--show-factor] [--conformable] [--output-
format format] [--product] [--quiet] [--silent] [--strict]
[--verbose] [--compact] [--one-line] [--terse] [--round]
[--unitsfile] [--units units system] [--version] [--info]
[from-unit [to-unit]]
๐ DESCRIPTION ๐
okay so. the units program takes quantities expressed in one system of measurement and converts them to their equivalents in another system of measurement. iconic behavior, honestly. like a bunch of similar programs it can do multiplicative scale changes โ easy, cute, done. but it can ALSO handle nonlinear conversions like Fahrenheit to Celsius (peep the Temperature Conversions section, iykyk). and it can do conversions from and to sums of units โ so yes bestie, it will convert between meters and feet-plus-inches. we love a flexible queen ๐
and before you come for me: "but Fahrenheit to Celsius is linear!!" no ma'am. not me getting called out. a transformationTis linear ifT(x + y) = T(x) + T(y)and that fails forT(x) = ax + b. that transformation is affine, not linear โ see https://en.wikipedia.org/wiki/Linear_map. the math said what it said ๐
basic operation is literally so simple: you enter the units you want to convert from and the units you want to convert to. you can run it interactively with prompts, or straight from the command line. both slay โจ
and beyond just plain unit conversion? units can be your general-purpose scientific calculator that keeps track of units in its calculations. you can build arbitrarily complex mathematical expressions of dimensions โ sums, products, quotients, powers, and even roots of dimensions. so when you're working with a long cursed expression involving a million different units that combine in unhinged ways, you can make sure everything stays accurate and dimensionally consistent. for a lil illustration of that, go look at Complicated Unit Expressions. no cap, it eats.
the units themselves live in several external data files. you can use the extensive data files that ship with the program, or bring your own data file to suit your needs ๐. you can also use your own data file to supplement the standard data files. mix and match, it's your world.
you can change the default behavior of units with all kinds of options on the command line. see Invoking Units for the deets on what's available.
๐ ADDITIONAL DOCUMENTATION ๐
this manual is also out here in PDF and HTML, besties:
https://www.gnu.org/software/units/manual/units.pdf
https://www.gnu.org/software/units/manual/units.html
๐ฆ INTERACTING WITH UNITS ๐ฆ
to invoke units for interactive use, just type units at your shell prompt. the program will print something like this:
Currency exchange rates from FloatRates (USD base) on 2023-07-08
3612 units, 109 prefixes, 122 nonlinear units
You have:
at the You have: prompt, type the quantity and units you're converting from. for example, if you wanna convert ten meters to feet, type 10 meters. next, units will print You want:. you should type the units you want to convert to. to convert to feet, you'd type feet. if the readline library was compiled in, then tab will complete unit names (see Readline Support for more about readline). to quit the program, type quit or exit at either prompt. bye bestie ๐
the result gets displayed in two ways. the first line of output is marked with a * to indicate multiplication, and it gives the result of the conversion you asked for. the second line is marked with a / to indicate division, and it gives the inverse of the conversion factor. so if you convert 10 meters to feet, units will print
* 32.808399
/ 0.03048
which tells you that 10 meters equals about 32.8 feet ๐. the second number gives the conversion in the opposite direction. in this case it's telling you that 1 foot is equal to about 0.03 dekameters, since the dekameter is 10 meters. it also tells you that 1/32.8 is about 0.03.
the units program prints the inverse because sometimes it's just the more convenient number, okay?? in the example above, the inverse value is an exact conversion: a foot is exactly 0.03048 dekameters. but the number given in the other direction is inexact. the way that matters ๐
if you convert grains to pounds, you'll see the following:
You have: grains
You want: pounds
* 0.00014285714
/ 7000
from that second line of output you can immediately see that a grain is equal to a seven thousandth of a pound. not so obvious from the first line, right? if the output format is confusing you, try the --verbose option:
You have: grain
You want: aeginamina
grain = 0.00010416667 aeginamina
grain = (1 / 9600) aeginamina
if you request a conversion between units that measure reciprocal dimensions, units will display the results with an extra lil note saying a reciprocal conversion has been done:
You have: 6 ohms
You want: siemens
reciprocal conversion
* 0.16666667
/ 6
reciprocal conversion can be suppressed with the --strict option. and as usual, --verbose gets you more comprehensible output:
You have: tex
You want: typp
reciprocal conversion
1 / tex = 496.05465 typp
1 / tex = (1 / 0.0020159069) typp
You have: 20 mph
You want: sec/mile
reciprocal conversion
1 / 20 mph = 180 sec/mile
1 / 20 mph = (1 / 0.0055555556) sec/mile
if you enter incompatible unit types, the units program will print a message telling you the units are not conformable, and it'll show you the reduced form for each unit:
You have: ergs/hour
You want: fathoms kg^2 / day
conformability error
2.7777778e-11 kg m^2 / sec^3
2.1166667e-05 kg^2 m / sec
if you only wanna find the reduced form or definition of a unit, just hit Enter at the You want: prompt. example time:
You have: jansky
You want:
Definition: fluxunit = 1e-26 W/m^2 Hz = 1e-26 kg / s^2
that output tells you the jansky is defined to be equal to a fluxunit, which is itself defined to be a certain combination of watts, meters, and hertz. the fully reduced (and in this case kinda more cryptic) form shows up on the far right. and if the ultimate definition and the fully reduced form are identical, the latter isn't shown at all:
You have: B
You want:
Definition: byte = 8 bit
the fully reduced form DOES show up if it and the ultimate definition are equivalent but not identical:
You have: N
You want:
Definition: newton = kg m / s^2 = 1 kg m / s^2
some named units are treated as dimensionless in some situations. these include the radian and steradian. in units conversions they get treated as equal to 1. power equals torque times angular velocity, and that conversion can only happen if the radian is dimensionless:
You have: (14 ft lbf) (12 radians/sec)
You want: watts
* 227.77742
/ 0.0043902509
you can also compute roots and other non-integer powers of dimensionless units, which lets you do computations like the altitude of geosynchronous orbit ๐:
You have: cuberoot(G earthmass / (circle/siderealday)^2) - earthradius
You want: miles
* 22243.267
/ 4.4957425e-05
โ ๏ธ named dimensionless units are NOT treated as dimensionless in other contexts, bestie. they can't be used as exponents โ so for example, meter^radian is forbidden. do not try her.
if you want a list of options, type ? at the You want: prompt. the program will show a list of named units that are conformable with the unit you entered at the You have: prompt above. note: conformable unit combinations will not appear on this list. okayyy ๐
๐ Interactive Commands ๐
typing help at either prompt displays a short help message. you can also type help followed by a unit name โ this invokes a pager on the units database at the point where that unit is defined, so you can read the definition and any comments that give more details or historical info about the unit ๐. if your pager allows it, you may wanna scroll backwards, e.g. with b, because sometimes a longer comment about a unit or group of units appears before the definition. you can generally quit out of the pager by pressing q.
typing search text displays a list of all units whose names contain text as a substring, along with their definitions. super helpful when you're not sure of the right unit name ๐. typing search . displays a list of all units โ helpful if you can't come up with an appropriate substring, though examining the output can be tedious, ngl. here . is a special argument to the search command, not a regular expression. if you DO want to use a regular expression to search units and their definitions, the --list-units option will display a list of all units, which you can pipe to a filter like grep. typing search _ displays a list of all assigned runtime variables โ whose names begin with _ โ without including all the units whose names simply contain _. see Variables Assigned at Run Time for more on runtime variables.
typing version displays the units version number; and unlike the --version option, only the version number is shown, regardless of any other settings. full information is available with the info command.
typing info displays the same information as the --info option, described in Invoking Units.
many values set by command-line options can also be set interactively by typing set option=value; typing set option will show the value for that option. typing set shows a list of options that can be set, and options set to anything other than their default values get a * prepended โญ. see Setting Options Interactively for more.
๐ USING UNITS NON-INTERACTIVELY ๐
okay so bestie, you don't have to sit there chatting with the prompt all day โ units can do the whole conversion thing non-interactively, straight from the command line. how? you just type the command, then the original unit expression, then the new units you want. that's it. that's the whole vibe.
quick heads up tho: if a units expression has non-alphanumeric characters in it, the shell might try to get cute and interpret them, so you may need to protect it with single or double quote characters. ๐ซถ
so if you type
units "2 liters" quarts
then units will print
* 2.1133764
/ 0.47317647
and then exit. and what that output is telling you is that 2 liters is about 2.1 quarts, or alternatively that a quart is about 0.47 times 2 liters. both readings, one slay conversion. โจ
and here's the thing โ units does not require a space between a numerical value and the unit. so the previous example can just be given as
units 2liters quarts
which saves you from having to quote the first argument at all. no quotes, no stress, no cap. ๐
if the conversion is successful, units will return success (zero) to the calling environment. but if you enter non-conformable units, then units will print a message giving the reduced form of each unit, and it will return failure (nonzero) to the calling environment. so the exit code is genuinely telling you the tea. ๐
if the --conformable option is given, only one unit expression is allowed, and units will print all units conformable with that expression โ it's equivalent to giving ? at the You want: prompt. for example,
units --conformable gauss
B_FIELD tesla
Gs gauss
T tesla
gauss abvolt sec / cm^2
stT stattesla
statT stattesla
stattesla statWb/cm^2
tesla Wb/m^2
look at all those conformable friends. the way they all match up?? iconic. ๐
โ ๏ธ if you give more than one unit expression with the --conformable option, the program will exit with an error message and return failure. one expression only, bestie. also note: this option has no effect in interactive mode.
and if the --terse (-t) option is given with the --conformable option, conformable units are shown without definitions. with the previous example, this would give
units --terse --conformable gauss
B_FIELD
Gs
T
gauss
stT
statT
stattesla
tesla
just the names, no explanations. minimal. clean. it's giving less is more. ๐
when the --conformable option is not given and you invoke units with only one argument, units will print the definition of the specified unit. it will return failure if the unit is not defined, and success if the unit is defined. so yeah โ one argument = definition reveal. ๐ฆ
๐ Finding Units ๐
so the units database includes many units, and ngl it can sometimes be difficult to remember every single name. the interactive search command only examines unit names, so it cannot be used to find units whose definitions contain a pattern. tragic, ik. ๐ญ
but!! if units is invoked with the --list-units option, the output can be sent to a filter such as grep, examining the unit name and the definition. for example,
units --list-units | grep ';'
dms deg;arcmin;arcsec
ftin ft;in;1|8 in
ftin16 ft;in;1|16 in
ftin32 ft;in;1|32 in
ftin4 ft;in;1|4 in
ftin64 ft;in;1|64 in
ftin8 ft;in;1|8 in
hms hr;min;sec
inchfine in;1|8 in;1|16 in;1|32 in;1|64 in
time year;day;hr;min;sec
uswt lb;oz
. . .
could find all unit lists, which include at least one semicolon in their definitions. semicolon girlies rise up. ๐
the search command doesn't support regular expressions, but with the --list-units option the output can be sent to a filter such as grep, which does. and if you expect a long list of results, you can send the output of the filter to a pager. for example,
units --list-units | grep 'paper[[:space:]]' | more
A0paper 841 mm 1189 mm
A10paper 26 mm 37 mm
A1paper 594 mm 841 mm
A2paper 420 mm 594 mm
A3paper 297 mm 420 mm
A4paper 210 mm 297 mm
A5paper 148 mm 210 mm
A6paper 105 mm 148 mm
A7paper 74 mm 105 mm
A8paper 52 mm 74 mm
A9paper 37 mm 52 mm
. . .
could show a list of all defined paper sizes. every paper size ever, piped straight to your eyeballs. obsessed. โจ
๐ UNIT DEFINITIONS ๐
okay so bestie, the conversion info is read from several units data files: definitions.units, elements.units, currency.units, and cpi.units, and theyโre usually located in the /usr/share/units directory. If you invoke units with the -V option, it will print the location of these files. The default main file includes definitions for all familiar units, abbreviations and metric prefixes. It also includes many obscure or archaic units. Many common spelled-out numbers (e.g., seventeen) are recognized. ๐
๐ซ Physical Constants ๐ซ
Many constants of nature are defined, including these:
piโ ratio of circumference of a circle to its diametercโ speed of lighteโ charge on an electronforceโ acceleration of gravitymoleโ Avogadroโs numberwaterโ pressure per unit height of waterHgโ pressure per unit height of mercuryauโ astronomical unitkโ Boltzmanโs constantmu0โ permeability of vacuumepsilon0โ permittivity of vacuumGโ Gravitational constantmachโ speed of sound
The standard data file includes numerous other constants. Also included are the densities of various ingredients used in baking so that 2 cups flour_sifted can be converted to grams. This is not an exhaustive list. Consult the units data file to see the complete list, or to see the definitions that are used. ๐ง
โ๏ธ Atomic Masses of the Elements โ๏ธ
The data file elements.units includes atomic masses for most elements and most known isotopes. If the mole fractions of constituent isotopes are known, an elemental mass is calculated from the sum of the products of the mole fractions and the masses of the constituent isotopes. If the mole fractions are not known, the mass of the most stable isotopeโif knownโis given as the elemental mass. For radioactive elements with atomic numbers 95 or greater, the mass number of the most stable isotope is not specified, because the list of studied isotopes is still incomplete. If no stable isotope is known, no elemental mass is given, and you will need to choose the most appropriate isotope. ๐
The data are obtained from the US National Institute for Standards and Technology (NIST): https://physics.nist.gov/cgi-bin/Compositions/stand_alone.pl?ele=&all=all&ascii=ascii2&isotype=all. The elements.units file can be generated from these data using the elemcvt command included with the distribution. โจ
๐ธ Currency Exchange Rates and Consumer Price Index ๐ธ
The data files currency.units, crypto.units, and metal_prices.units include currency conversion rates, cryptocurrency prices, and the prices of precious metals. The file cpi.units includes the US Consumer Price Index (CPI), published by the US Bureau of Labor Statistics; the data are updated monthly by the BLS. See Updating Currency Exchange Rates and CPI for information on updating currency.units, crypto.units, metal_prices.units, and cpi.units. ๐ธ
๐ฌ๐ง English Customary Units ๐บ๐ธ
English customary units differ in various ways among different regions. In Britain a complex system of volume measurements featured different gallons for different materials such as a wine gallon and ale gallon that differ by twenty percent. This complexity was swept away in 1824 by a reform that created an entirely new gallon, the British Imperial gallon defined as the volume occupied by ten pounds of water. Meanwhile in the USA the gallon is derived from the 1707 Winchester wine gallon, which is 231 cubic inches. These gallons differ by about twenty percent. By default if units runs in the en_GB locale you will get the British volume measures. If it runs in the en_US locale you will get the US volume measures. In other locales the default values are the US definitions. If you wish to force different definitions, then set the environment variable UNITS_ENGLISH to either US or GB to set the desired definitions independent of the locale. ๐บ๐ธ๐ฌ๐ง
Before 1959, the value of a yard (and other units of measure defined in terms of it) differed slightly among English-speaking countries. In 1959, Australia, Canada, New Zealand, the United Kingdom, the United States, and South Africa adopted the Canadian value of 1 yard = 0.9144 m (exactly), which was approximately halfway between the values used by the UK and the US; it had the additional advantage of making 1 inch = 2.54 cm (exactly). This new standard was termed the International Yard. Australia, Canada, and the UK then defined all customary lengths in terms of the International Yard (Australia did not define the furlong or rod); because many US land surveys were in terms of the pre-1959 units, the US continued to define customary surveyorsโ units (furlong, chain, rod, pole, perch, and link) in terms of the previous value for the foot, which was termed the US survey foot. The US defined a US survey mile as 5280 US survey feet, and defined a statute mile as a US survey mile. The US values for these units differed from the international values by about 2 ppm. ๐
The 1959 redefinition of the foot was legally binding in the US but allowed continued use of the previous definition of the foot for geodetic surveying. It was assumed that this use would be temporary, but use persisted, leading to confusion and errors, and it was at odds with the intent of uniform standards. Since January 1, 2023, the US survey foot has been officially deprecated (85 FR 62698), with its use limited to historical and legacy applications. ๐ซ
The units program has always used the international values for these units; the legacy US values can be obtained by using either the US or the survey prefix. In either case, the simple familiar relationships among the units are maintained, e.g., 1 furlong = 660 ft, and 1 USfurlong = 660 USft, though the metric equivalents differ slightly between the two cases. The US prefix or the survey prefix can also be used to obtain the US survey mile and the value of the US yard prior to 1959, e.g., USmile or surveymile (but not USsurveymile). To get the US value of the statute mile, use either USstatutemile or USmile. The pre-1959 UK values for these units can be obtained with the prefix UK. ๐
Except for distances that extend over hundreds of miles (such as in the US State Plane Coordinate System), the differences in the miles are usually insignificant:
You have: 100 surveymile - 100 mile
You want: inch
* 12.672025
/ 0.078913984
The US acre was officially defined in terms of the US survey foot, but units has used a definition based on the international foot; the units definition is now the same as the official US value. If you want the previous US acre, use USacre and similarly use USacrefoot for the previous US version of that unit. The difference between these units is about 4 parts per million. ๐ฝ
๐งธ Miscellaneous Notes on Unit Definitions ๐งธ
The pound is a unit of mass. To get force, multiply by the force conversion unit force or use the shorthand lbf. (Note that g is already taken as the standard abbreviation for the gram.) The unit ounce is also a unit of mass. The fluid ounce is fluidounce or floz. When British capacity units differ from their US counterparts, such as the British Imperial gallon, the unit is defined both ways with br and us prefixes. Your locale settings will determine the value of the unprefixed unit. Currency is prefixed with its country name: belgiumfranc, britainpound. ๐ธ
When searching for a unit, if the specified string does not appear exactly as a unit name, then the units program will try to remove a trailing s, es. Next units will replace a trailing ies with y. If that fails, units will check for a prefix. The database includes all of the standard metric prefixes. Only one prefix is permitted per unit, so micromicrofarad will fail. However, prefixes can appear alone with no unit following them, so micro*microfarad will work, as will micro microfarad. ๐
To find out which units and prefixes are available, read the default units data files; the main data file is extensively annotated. ๐
๐งฎ UNIT EXPRESSIONS ๐งฎ
โ Operators โ
You can enter more complicated units by combining units with operations such as multiplication, division, powers, addition, subtraction, and parentheses for grouping. You can use the customary symbols for these operators when units is invoked with its default options. Additionally, units supports some extensions, including high priority multiplication using a space, and a high priority numerical division operator (|) that can simplify some expressions. โจ
You multiply units using a space or an asterisk (*). The next example shows both forms:
You have: arabicfoot * arabictradepound * force
You want: ft lbf
* 0.7296
/ 1.370614
You can divide units using the slash (/) or with per:
You have: furlongs per fortnight
You want: m/s
* 0.00016630986
/ 6012.8727
You can use parentheses for grouping:
You have: (1/2) kg / (kg/meter)
You want: league
* 0.00010356166
/ 9656.0833
White space surrounding operators is optional, so the previous example could have used (1/2)kg/(kg/meter). As a consequence, however, hyphenated spelled-out numbers (e.g., forty-two) cannot be used; forty-two is interpreted as 40 - 2. ๐ญ
Multiplication using a space has a higher precedence than division using a slash and is evaluated left to right; in effect, the first / character marks the beginning of the denominator of a unit expression. This makes it simple to enter a quotient with several terms in the denominator: J / mol K. The * and / operators have the same precedence, and are evaluated left to right; if you multiply with *, you must group the terms in the denominator with parentheses: J / (mol * K). ๐ฅ
The higher precedence of the space operator may not always be advantageous. For example, m/s s/day is equivalent to m / s s day and has dimensions of length per time cubed. Similarly, 1/2 meter refers to a unit of reciprocal length equivalent to 0.5/meter, perhaps not what you would intend if you entered that expression. To get a half meter you would need to use parentheses: (1/2) meter. The * operator is convenient for multiplying a sequence of quotients. For example, m/s * s/day is equivalent to m/day. Similarly, you could write 1/2 * meter to get half a meter. ๐
Okay bestie, buckle up, because the units program has โจanotherโจ way to do fractions, and it's lowkey iconic: you can show division of numbers with the vertical bar (|). So if you wanted half a meter, you'd just write 1|2 meter ๐
. But heads up โ you cannot use the vertical bar to divide non-numerical units (so m|s is gonna throw an error message at you, no cap ๐).
Powers of units? Two ways, bestie. Either the ^ character, like in the example below, or just smush a unit and its exponent together: cm3 is equivalent to cm^3. If the exponent is more than one digit though, you have to use the ^. You can also use ** as an exponent operator ๐.
You have: cm^3
You want: gallons
* 0.00026417205
/ 3785.4118
Concatenation only works with a single unit name, okay? If you write (m/s)2, units is gonna treat that as multiplication by 2. And when a unit includes a prefix, exponent operators apply to the whole combination, so centimeter3 gives you cubic centimeters ๐ง. But if you separate the prefix from the unit with any multiplication operator (like centi meter^3), the prefix gets treated as a separate unit, so the exponent only applies to the unit without the prefix. That second one is equivalent to centi * (meter^3), and it gives you a hundredth of a cubic meter โ not a cubic centimeter, bestie, they're different!! ๐ญ
Also the units program is limited internally to products of 99 units, so expressions like meter^100 or joule^34 (which is represented internally as kg^34 m^68 / s^68) will straight-up fail ๐.
The | operator has the highest precedence, so you can write the square root of two thirds as 2|3^1|2. The ^ operator has the second highest precedence, and it's evaluated right to left, as usual:
You have: 5 * 2^3^2
You want:
Definition: 2560
With a dimensionless base unit, any dimensionless exponent is meaningful (e.g., pi^exp(2.371)). Even though angle is sometimes treated as dimensionless, exponents cannot have dimensions of angle, periodt:
You have: 2^radian
^
Exponent not dimensionless
If the base unit is not dimensionless, the exponent has to be a rational number p/q, and the dimension of the unit must be a power of q. So gallon^2|3 works but acre^2|3 fails ๐ธ. An exponent using the slash (/) operator (e.g., gallon^(2/3)) is also acceptable โ the parentheses are needed because the precedence of ^ is higher than that of /. And since units cannot represent dimensions with exponents greater than 99, a fully reduced exponent must have q < 100. When you raise a non-dimensionless unit to a power, units attempts to convert a decimal exponent to a rational number with q < 100. If that's not possible, units hits you with an error message:
You have: ft^1.234
Base unit not dimensionless; rational exponent required
A decimal exponent must match its rational representation to machine precision, so acre^1.5 works but gallon^0.666 does not ๐
๐ Sums and Differences of Units ๐
Sometimes you wanna add values of different units that live outside the SI. And sometimes you just wanna use units as a calculator that keeps track of units for you, which is honestly so valid ๐ซถ. Sums of conformable units are written with the + character, and differences with the - character.
You have: 2 hours + 23 minutes + 32 seconds
You want: seconds
* 8612
/ 0.00011611705
You have: 12 ft + 3 in
You want: cm
* 373.38
/ 0.0026782366
You have: 2 btu + 450 ft lbf
You want: btu
* 2.5782804
/ 0.38785542
The expressions that get added or subtracted must reduce to identical expressions in primitive units, or you'll get an error message:
You have: 12 printerspoint - 4 heredium
^
Invalid sum of non-conformable units
If you add two values of vastly different scale, you may exceed the available precision of floating point (about 15 digits). The effect? The addition of the smaller value makes no change to the larger value โ in other words, the smaller value is treated as if it were zero ๐ญ.
You have: lightyear + cm
No warning is given, however ๐. As usual, the precedence for + and - is lower than that of the other operators. A fractional quantity like 2 1/2 cups can be given as (2+1|2) cups โ the parentheses are necessary because multiplication has higher precedence than addition. If you omit the parentheses, units attempts to add 2 and 1|2 cups, and you get an error message:
You have: 2+1|2 cups
^
Invalid sum or difference of non-conformable units
You could also correctly write it as (2+1/2) cups. But if you write 2 1|2 cups, the space is interpreted as multiplication, so the result is the same as 1 cup ๐.
The + and - characters sometimes appear in exponents like 3.43e+8. This leads to an ambiguity in an expression like 3e+2 yC. The unit e is a small unit of charge, so this can be regarded as equivalent to (3e+2) yC or (3 e)+(2 yC). This ambiguity is resolved by always interpreting + and - as part of an exponent if possible โจ.
๐ข Numbers as Units ๐ข
For units, numbers are just another kind of unit, bestie. They can appear as many times as you like and in any order in a unit expression. For example, to find the volume of a box that is 2 ft by 3 ft by 12 ft in steres, you could do this:
You have: 2 ft 3 ft 12 ft
You want: stere
* 2.038813
/ 0.49048148
You have: $ 5 / yard
You want: cents / inch
* 13.888889
/ 0.072
And that second example shows how the dollar sign in the units conversion can precede the five ๐
. But be careful: units will interpret $5 with no space as equivalent to dollar^5. Sneaky!!
๐ Built-in Functions ๐
Several built-in functions are provided: sin, cos, tan, secant, csc, cot, asin, acos, atan, asecant, acsc, acot, sinh, cosh, tanh, sech, csch, coth, asinh, acosh, atanh, asech, acsch, acoth, exp, ln, log, abs, round, floor, ceil, factorial, Gamma, lnGamma, erf, and erfc. The function lnGamma is the natural logarithm of the Gamma function ๐งฎ.
The sin, cos, tan, secant, csc and cot functions require either a dimensionless argument or an argument with dimensions of angle.
You have: sin(30 degrees)
You want:
Definition: 0.5
You have: sin(pi/2)
You want:
Definition: 1
You have: sin(3 kg)
^
Unit not dimensionless
The other functions on the list require dimensionless arguments. And the inverse trigonometric functions return arguments with dimensions of angle ๐ธ.
The ln and log functions give natural log and log base 10 respectively. To obtain logs for any integer base, enter the desired base immediately after log. So for log base 2 you'd write log2, and for log base 47 you could write log47 โญ.
You have: log2(32)
You want:
Definition: 5
You have: log3(32)
You want:
Definition: 3.1546488
You have: log4(32)
You want:
Definition: 2.5
You have: log32(32)
You want:
Definition: 1
You have: log(32)
You want:
Definition: 1.50515
You have: log10(32)
You want:
Definition: 1.50515
If you wish to take roots of units, you may use the sqrt or cuberoot functions. These functions require that the argument have the appropriate root. You can obtain higher roots by using fractional exponents ๐:
You have: sqrt(acre)
You want: feet
* 208.71074
/ 0.0047913202
You have: (400 W/m^2 / stefanboltzmann)^(1/4)
You have:
Definition: 289.80882 K
You have: cuberoot(hectare)
^
Unit not a root
๐ Previous Result ๐
You can insert the result of the previous conversion using the underscore (_). It's useful when you wanna convert the same input to several different units, like this:
You have: 2.3 tonrefrigeration
You want: btu/hr
* 27600
/ 3.6231884e-005
You have: _
You want: kW
* 8.0887615
/ 0.12362832
Suppose you wanna do some deep frying that requires an oil depth of 2 inches. You have 1/2 gallon of oil, and want to know the largest-diameter pan that will maintain the required depth. The nonlinear unit circlearea gives the radius of the circle (see Other Nonlinear Units, for a more detailed description) in SI units; you want the diameter in inches:
You have: 1|2 gallon / 2 in
You want: circlearea
0.10890173 m
You have: 2 _
You want: in
* 8.5749393
/ 0.1166189
In most cases, surrounding white space is optional, so the previous example could have used 2_. If _ follows a non-numerical unit symbol, however, the space is required:
You have: m_
^
Parse error
You can use the _ symbol any number of times; for example,
You have: m
You want:
Definition: 1 m
You have: _ _
You want:
Definition: 1 m^2
Using _ before a conversion has been performed (e.g., immediately after invocation) generates an error:
You have: _
^
No previous result; '_' not set
Accordingly, _ serves no purpose when units is invoked non-interactively ๐.
If units is invoked with the --verbose option (see Invoking Units), the value of _ is not expanded:
You have: mile
You want: ft
mile = 5280 ft
mile = (1 / 0.00018939394) ft
You have: _
You want: m
_ = 1609.344 m
_ = (1 / 0.00062137119) m
You can give _ at the You want: prompt, but it usually is not very useful ๐.
๐ฆ Complicated Unit Expressions ๐ฆ
The units program is especially helpful in ensuring accuracy and dimensional consistency when converting lengthy unit expressions, and honestly? That's the moment. ๐
For example, one form of the Darcy-Weisbach fluid-flow equation is
Delta P = (8 / pi)^2 (rho fLQ^2) / d^5,
where Delta P is the pressure drop, rho is the mass density, f is the (dimensionless) friction factor, L is the length of the pipe, Q is the volumetric flow rate, and d is the pipe diameter. You might want to have the equation in the form
Delta P = A1 rho fLQ^2 / d^5
that was like, accepting the user's normal units, bestie. For the typical units used in the US, the conversion you need could be something like
You have: (8/pi^2)(lbm/ft^3)ft(ft^3/s)^2(1/in^5)
You want: psi
* 43.533969
/ 0.022970568
The parentheses let you drop individual terms into the expression naturally, exactly like you'd read them off the formula. โจ Or, you could do the multiplication with * instead of a space โ and then you only need parens around ft^3/s because of that little exponent situation:
You have: 8/pi^2 * lbm/ft^3 * ft * (ft^3/s)^2 /in^5
You want: psi
* 43.533969
/ 0.022970568
No parentheses and using spaces for multiplication, the same conversion would need to be typed as
You have: 8 lb ft ft^3 ft^3 / pi^2 ft^3 s^2 in^5
You want: psi
* 43.533969
/ 0.022970568
๐ธ Variables Assigned at Run Time ๐ธ
Unit definitions are locked in once units has finished reading the units data file(s) โ no takebacks, no edits. BUT at run time you can assign unit expressions to variables whose names begin with an underscore, using this syntax:
_name = <unit expression>
This is lowkey a lifesaver for managing a long calculation โ you save intermediate quantities as variables and reuse them later. ๐ For example, to find the shot-noise-limited signal-to-noise ratio (SNR) of an imaging system using a heliumโneon laser, you could do
You have: _lambda = 632.8 nm # laser wavelength
You have: _nu = c / _lambda # optical frequency
You have: _photon_energy = h * _nu
You have: _power = 550 uW
You have: _photon_count = _power * 500 ns / _photon_energy
You have: _snr = sqrt(_photon_count)
You have: _snr
You want:
Definition: sqrt(_photon_count) = 29597.922
Other than the underscore at the front, runtime variables follow the exact same naming rules as units. And because names starting with _ are reserved for these variables, and unit names can't start with _, runtime variables can never hide unit definitions. ๐ซถ Runtime variables are undefined until you actually assign something to them, so if you type a name starting with an underscore and no assignment has happened yet, you get an error message.
When you assign a unit expression to a runtime variable, units checks the expression to make sure it's valid, but the resulting definition is stored as a text string that is not reduced to primitive units. That text gets processed anew every single time you use the variable in a conversion or calculation. Which means: if your definition depends on other runtime variables (or the special variable _), the result of calculating with your variable will change if any of those variables change. And the dependence doesn't even need to be direct. ๐ญ
Continuing the laser example above โ say you've done the calculation as shown. Now you're wondering what happens if you switch to an argon laser:
You have: _lambda = 454.6 nm
You have: _snr
You want:
Definition: sqrt(_photon_count) = 25086.651
And if you then change the power:
You have: _power = 1 mW
You have: _snr
You want:
Definition: sqrt(_photon_count) = 33826.834
Instead of having to reenter or edit some lengthy expression every time you do another calculation, you only need to enter the values that change. In this respect, runtime variables are basically a spreadsheet. ๐โจ
The more times a variable shows up in an expression that depends on it, the bigger the payoff of having a calculation with that expression reflect changes to that variable. For example, the length of daylight โ the time the Sun is above the horizon โ at a given latitude and declination of the Sun is given by
L = acos((sin h - sin ฯ sin ฮด) /
(cos ฯ cos ฮด))
where L is the day length, h is the altitude, ฯ is the latitude, and ฮด is the Sun's declination.
The result above is in sidereal time; the length in solar time is obtained by multiplying by
siderealday / day
By convention, the Sun's altitude at rise or set is -50โฒ to allow for atmospheric refraction and the semidiameter of its disk. At the summer solstice in the northern hemisphere, the Sun's declination is approximately 23.44ยฐ; to find the length of the longest day of the year for a latitude of 55ยฐ, you could do
You have: _alt = -50 arcmin
You have: _lat = 55 deg
You have: _decl = 23.44 deg
You have: _num = sin(_alt) - sin(_lat) sin(_decl)
You have: _denom = cos(_lat) cos(_decl)
You have: _sday = 2 (acos(_num / _denom) / circle) 24 hr
You have: _day = _sday siderealday / day
You have: _day
You want: hms
17 hr + 19 min + 34.895151 sec
At the winter solstice, the Sun's declination is approximately -23.44ยฐ, so you could calculate the length of the shortest day of the year using:
You have: _decl = -23.44 deg
You have: _day
You want: hms
7 hr + 8 min + 40.981084 sec
Latitude and declination each appear twice in the expression for _day; the result in the examples above updates by changing only the value of the declination. ๐ง
Now โ it might seem easier (and less error-prone) to just specify the new value of _decl as the negative of the current value (like, _decl = -_decl). This doesn't work. When you make an assignment with the = operator, the definition is stored as entered, including possible dependencies on variables. But if you attempt an assignment that's ultimately self-referential, the current definition is retained, and you get an error message. For example,
You have: _decl = 23.44 deg
You have: _decl = -_decl
Circular unit definition
You can get around this with the := operator, which reduces the right hand side to primitive units before making the assignment โ eliminating any dependencies on variables. Back to the example:
You have: _decl = 23.44 deg
You have: _decl = -_decl
Circular unit definition
You have: _decl := -_decl
You have: _decl
You want: deg
* -23.44
/ -0.042662116
This works to much the same effect as if the assignment had been entered literally, e.g.,
You have: _decl = -23.44 deg
but the actual definition is in primitive units โ in this case, radians:
You have: _decl = 23.44 deg
You have: _decl := -_decl
You have: _decl
You want:
Definition: -0.40910517666747087 radian = -0.40910518 radian
Definitions are text strings, and a redefinition using := is given with enough digits to maintain the full precision of the current definition when converted back to a number; because it's a string, all digits are displayed when showing the definition, regardless of the numerical display precision, so you may see more digits than you expected. ๐
A runtime variable has to be assigned before it can be used in an assignment โ in the first of the three examples above, giving the general equation before the values for_alt,_lat, and_declhad been assigned would result in an error message.
You can display a list of runtime variables you've assigned by typing search _.
๐ Backwards Compatibility: * and - ๐
The original units gave multiplication a higher precedence than division using the slash. This differs from the usual precedence rules, which give multiplication and division equal precedence, and can be confusing for people who think of units as a calculator.
The star operator (*) included in this units program has, by default, the same precedence as division, and therefore follows the usual precedence rules. For backwards compatibility you can invoke units with the --oldstar option. Then * has a higher precedence than division, and the same precedence as multiplication using the space.
Historically, the hyphen (-) has been used in technical publications to indicate products of units, and the original units program treated it as a multiplication operator. Because units provides several other ways to obtain unit products, and because - is a subtraction operator in general algebraic expressions, units treats the binary - as a subtraction operator by default. For backwards compatibility use the --product option, which causes units to treat the binary - operator as a product operator. When - is a multiplication operator it has the same precedence as multiplication with a space, giving it a higher precedence than division.
When - is used as a unary operator it negates its operand. Regardless of the units options, if - appears after ( or after +, then it will act as a negation operator. So you can always compute 20 degrees minus 12 minutes by entering 20 degrees + -12 arcmin. You must use this construction when you define new units, because you cannot know what options will be in force when your definition is processed. โ ๏ธ
๐ NONLINEAR UNIT CONVERSIONS ๐
Nonlinear units are represented using functional notation. They make possible nonlinear unit conversions such as temperature. ๐ฅต๐ฅถ
๐ Temperature Conversions ๐
Conversions between temperatures are different from linear conversions between temperature increments โ see the example below. The absolute temperature conversions are handled by units starting with temp, and you must use functional notation. The temperature-increment conversions are done using units starting with deg and they do not require functional notation.
You have: tempF(45)
You want: tempC
7.2222222
You have: 45 degF
You want: degC
* 25
/ 0.04
Think of tempF(x) not as a function but as a notation that indicates that x should have units of tempF attached to it. See Defining Nonlinear Units. The first conversion shows that if it's 45 degrees Fahrenheit outside, it's 7.2 degrees Celsius. The second conversion indicates that a change of 45 degrees Fahrenheit corresponds to a change of 25 degrees Celsius. The conversion from tempF(x) is to absolute temperature, so that
You have: tempF(45)
You want: degR
* 504.67
/ 0.0019814929
gives the same result as
You have: tempF(45)
You want: tempR
* 504.67
/ 0.0019814929
But if you convert tempF(x) to degC, the output is probably not what you expect:
You have: tempF(45)
You want: degC
* 280.37222
/ 0.0035666871
The result is the temperature in K, because degC is defined as K, the kelvin. For consistent results, use the tempX units when converting to a temperature rather than converting a temperature increment. ๐
โจ
The tempC() and tempF() definitions are strictly limited to positive absolute temperatures, bestie. Hand them a value that would land you at a negative absolute temperature and they will absolutely drag you with an error message:
You have: tempC(-275)
^
Argument of function outside domain
๐ธ US Consumer Price Index ๐ธ
units ships with the US Consumer Price Index published by the US Bureau of Labor Statistics, no cap. There's a whole lil friend group of functions riding on it: cpi, cpi_now, inflation_since, and dollars_in.
The cpi function hands you the CPI for a specified decimal year. A decimal year is literally just the year plus the fractional chunk of the year โ and because of leap years and months being wildly different lengths, working out an exact fractional value is tedious af, but for CPI purposes an approximate value is usually plenty. For example: 1 January 2000 is 2000.0, 1 April 2000 is 2000.25, 1 July 2000 is 2000.4986, and 1 October 2000 is 2000.75. Also worth knowing: the CPI data update monthly, and values in between months are linearly interpolated. โจ
In the middle of 1975, the CPI was
You have: cpi(1975.5)
You want:
Definition: 53.6
The value of the CPI for a month usually gets published sometime around the 20th day of the following month, and the latest value is available with cpi_now. On 7 January 2024, the value was
You have: cpi_now
You want:
Definition: UScpi_now = 307.051
This means that the CPI was 307.015 on 1 December 2023. The cpi_now variable can only present the most recent data available, so it can lag the current CPI by several weeks. The decimal year of the last update is available with cpi_lastdate. ๐
The inflation_since function is the convenient lil shortcut for figuring out the inflation factor from a specified decimal year to the latest value in the CPI table. For example, on 7 January 2024:
You have: inflation_since(1970)
You want:
Definition: 8.1445889
In other words, goods that cost 1 US$ in 1970 would cost 8.14 US$ on 1 December 2023. ๐ซถ
You can also use inflation_since to work out an annual rate of inflation. The earliest US CPI data are from about 1913.1; the approximate time between then and 7 January 2024 is 110.9 years. The approximate annual inflation rate for that period is then
You have: inflation_since(1913.1)^1|110.9 - 1
You want: %
* 3.1548115
/ 0.31697614
And the inflation rate for any time period can be found from the ratio of the CPI at the end of the period to that of the beginning:
You have: (cpi(1982)/cpi(1972))^1|10 - 1
You want: %
* 8.6247033
/ 0.11594602
The period 1972โ1982 was indeed one of high inflation, bestie. ๐ญ
The dollars_in function is basically inflation_since's sibling, except its output is in US$ rather than dimensionless:
You have: dollars_in(1970)
You want:
Definition: 8.1445889 US$
A typical use might be
You have: 250 dollars_in(1970)
You want: $
* 2036.1472
/ 0.00049112362
Because dollars_in already includes the units, you should not include them at the You have: prompt. You can also use dollars_in to convert between two specified years:
You have: 250 dollars_in(1970)
You want: dollars_in(1950)
* 156.49867
/ 0.0063898305
which shows that 250 US$ in 1970 would have equivalent purchasing power to 156 US$ in 1950. iconic tbh ๐
๐ฆ Other Nonlinear Units ๐ฆ
Some other examples of nonlinear units are numerous different ring sizes and wire gauges, screw gauges, pipe and tubing sizes, the grit sizes used for abrasives, the decibel scale, shoe size, scales for the density of sugar (e.g., baume). The standard data file also supplies units for computing the area of a circle and the volume of a sphere. See the standard units data file for more details. ๐
Diameters of American wire sizes can be found using the wiregauge() function or its alias awg():
You have: wiregauge(11)
You want: inches
* 0.090742002
/ 11.020255
You have: 1 mm
You want: wiregauge
18.201919
Wire and screw gauges with multiple zeroes are signified using negative numbers, where two zeroes (โ00โ; โ2/0โ) is -1, three zeros (โ000โ; โ3/0โ) is -2, and so on. Alternatively, you can use the synonyms g00, g000, or g2_0, g3_0, and so on that are defined in the standard units data file.
You have: brwiregauge(g00)
You want: inches
* 0.348
/ 2.8735632
In North America, wire sizes larger than 0000 (โ4/0โ) are usually given in terms of area, either in kcmil or the older initialism MCM (thousand circular mils). Outside of North America, all wire sizes are usually given in terms of area in mm^2. Wire area can be obtained using wiregaugeA() or its alias awgA():
You have: awgA(g6_0)
You want: kcmil
* 336.45718
/ 0.0029721464
You have: awgA(12)
You want: mm^2
* 3.3087729
/ 0.30222685
The closest standard metric sizes are 2.5 mm^2 and 4 mm^2; in general, there isn't an exact correlation between American and metric wire sizes. ๐คท
Though it's based on the long-established iron pipe size (IPS) given in inches, nominal pipe size (NPS) is a dimensionless quantity that corresponds to the inch size. Pipe size can be equivalently specified using metric diamรจtre nominal (DN), which roughly corresponds to the diameter in mm. For a given pipe size, outside diameter is constant while inside diameter varies with schedule. For example, for NPS 2ยฝ pipe,
You have: npsOD(2+1|2)
You want: in
* 2.875
/ 0.34782609
You have: nps40(2+1|2)
You want: in
* 2.469
/ 0.40502228
You have: nps80(2+1|2)
You want: in
* 2.323
/ 0.43047783
Pipe size can be given equivalently in terms of the metric DN by using the DN() function, which converts nominal metric size to nominal inch size:
You have: npsOD(DN(65))
You want: mm
* 73.025
/ 0.01369394
You have: _
You want: in
* 2.875
/ 0.34782609
Unlike with wire sizes, actual NPS and metric DN pipe dimensions are the same. ๐
You have: grit_P(600)
You want: grit_ansicoated
342.76923
The last example shows the conversion from P graded sand paper, which is the European standard and may be marked โP600โ on the back, to the USA standard.
You can compute the area of a circle using the nonlinear unit, circlearea. You can also do this using the circularinch or circleinch. The next example shows two ways to compute the area of a circle with a five inch radius and one way to compute the volume of a sphere with a radius of one meter.
You have: circlearea(5 in)
You want: in2
* 78.539816
/ 0.012732395
You have: 10^2 circleinch
You want: in2
* 78.539816
/ 0.012732395
You have: spherevol(meter)
You want: ft3
* 147.92573
/ 0.0067601492
The inverse of a nonlinear conversion is indicated by prefixing a tilde (~) to the nonlinear unit name:
You have: ~wiregauge(0.090742002 inches)
You want:
Definition: 11
You can give a nonlinear unit definition without an argument or parentheses, and press Enter at the You want: prompt to get the definition of a nonlinear unit; if the definition is not valid for all real numbers, the range of validity is also given. If the definition requires specific units this information is also displayed:
You have: tempC
Definition: tempC(x) = x K + stdtemp
defined for x >= -273.15
You have: ~tempC
Definition: ~tempC(tempC) = (tempC +(-stdtemp))/K
defined for tempC >= 0 K
You have: circlearea
Definition: circlearea(r) = pi r^2
r has units m
To see the definition of the inverse use the ~ notation. In this case the parameter in the functional definition will usually be the name of the unit. Note that the inverse for tempC shows that it requires units of K in the specification of the allowed range of values. Nonlinear unit conversions are described in more detail in Defining Nonlinear Units. ๐
๐ Multivariate Functions ๐
The units program supports some multivariate functions for performing calculations with units. The hypot function computes the length of a hypotenuse given two sides. It works with any pair of values that have compatible dimensions.
You have: hypot(3 m, 4 m)
You want:
Definition: 5 m
You can compute wind chill, based on temperature and wind speed, or heat index, based on temperature and humidity, with humidity given as a fraction, e.g., 0.5 for a 50% relative humidity.
You have: windchill(tempF(28), 14 mph)
You want: tempF
16.86826
You have: heatindex(tempC(40),0.5)
You want: tempC
54.767952
Both wind chill and heat index return a value that is nominally a temperature, so you will want to convert it to Fahrenheit or Celsius as shown in order to get a meaningful numerical value. ๐ง
โจ UNIT LISTS: CONVERSION TO SUMS OF UNITS โจ
okay bestie so outside of the SI system, sometimes you genuinely want to turn one unit into a sum of units โ like, feet into feet <em>plus</em> inches. the conversion from sums of units was already covered in Sums and Differences of Units, and honestly it's not that deep โ you just add the units with the โ+โ sign:
You have: 12 ft + 3 in + 3|8 in
You want: ft
* 12.28125
/ 0.081424936
and yeah, you can write a sum of units on the "You want:" side too, but heads up โ the result won't be the conversion to the units in the sum, it'll be the conversion to that particular sum you typed. so:
You have: 12.28125 ft
You want: ft + in + 1|8 in
* 11.228571
/ 0.089058524
the unit expression at the โYou want:โ prompt is equivalent to asking for conversion to multiples of โ1 ft + 1 in + 1|8 inโ, which is 1.09375 ft, so that whole thing is really just:
You have: 12.28125 ft
You want: 1.09375 ft
* 11.228571
/ 0.089058524
when you're converting to a sum of units like miles, feet and inches, what you actually want is the largest integral value for the first unit, then the largest integral value for the next, and whatever's left over goes to the last unit. units has a special syntax for lists of units that does this for you ๐. you must list the desired units in order from largest to smallest, separated by the semicolon (โ;โ) character:
You have: 12.28125 ft
You want: ft;in;1|8 in
12 ft + 3 in + 3|8 in
the conversion always gives integer coefficients on the units in the list โ <em>except possibly the last unit</em>, when the conversion isn't exact:
You have: 12.28126 ft
You want: ft;in;1|8 in
12 ft + 3 in + 3.00096 * 1|8 in
and the order you list them in matters, no cap:
You have: 3 kg
You want: oz;lb
105 oz + 0.051367866 lb
You have: 3 kg
You want: lb;oz
6 lb + 9.8218858 oz
listing ounces before pounds gives you a result that's technically correct but likeโฆ not useful? ๐ you have to list the units in descending order of size to get the most useful result.
ending a unit list with the separator โ;โ has the same effect as repeating the last unit on the list, so โft;in;1|8 in;โ is equivalent to โft;in;1|8 in;1|8 inโ. with the example above, that gives:
You have: 12.28126 ft
You want: ft;in;1|8 in;
12 ft + 3 in + 3|8 in + 0.00096 * 1|8 in
which basically separates the integer and fractional parts of the coefficient for the last unit. if you'd rather <em>round</em> that last coefficient to an integer, the โ--roundโ (โ-rโ) option is right there. same example, and you get:
You have: 12.28126 ft
You want: ft;in;1|8 in
12 ft + 3 in + 3|8 in (rounded down to nearest 1|8 in)
when you use โ-rโ, repeating the last unit on the list has no effect (like, โft;in;1|8 in;1|8 inโ is equivalent to โft;in;1|8 inโ), and so ending a list with a โ;โ does nothing either. but with a single unit and the โ-rโ option, a terminal โ;โ does have an effect: it makes units treat the single unit as a list and produce a rounded value for it. without that extra โ;โ, the โ-rโ option has no effect on single unit conversions. here's the output with โ-rโ:
You have: 12.28126 ft
You want: in
* 147.37512
/ 0.0067854058
You have: 12.28126 ft
You want: in;
147 in (rounded down to nearest in)
every unit in the list has to be conformable with the first unit on the list, and obviously the listed units also have to be conformable with whatever you entered at the โYou have:โ prompt.
You have: meter
You want: ft;kg
^
conformability error
ft = 0.3048 m
kg = 1 kg
You have: meter
You want: lb;oz
conformability error
1 m
0.45359237 kg
in the first case, units reports the disagreement <em>between units appearing on the list</em>. in the second, units reports disagreement between <em>the unit you entered and the desired conversion</em>. and this conformability error is based on the first unit on the unit list, fyi.
other common candidates for conversion to sums of units are angles and time:
You have: 23.437754 deg
You want: deg;arcmin;arcsec
23 deg + 26 arcmin + 15.9144 arcsec
You have: 7.2319 hr
You want: hr;min;sec
7 hr + 13 min + 54.84 sec
some applications for unit lists are less obvious ๐. say you have a postal scale and you want to make sure it's accurate at 1 oz, but all you have are metric calibration weights. you might try:
You have: 1 oz
You want: 100 g;50 g; 20 g;10 g;5 g;2 g;1 g;
20 g + 5 g + 2 g + 1 g + 0.34952312 * 1 g
then you'd place one each of the 20 g, 5 g, 2 g, and 1 g weights on the scale and hope it reads close to:
You have: 20 g + 5 g + 2 g + 1 g
You want: oz;
0.98767093 oz
appending โ;โ to โozโ forces a one-line display that includes the unit โ here the integer part of the result is zero, so it just doesn't get shown ๐ซถ.
if a non-empty list item differs vastly in scale from the quantity you're converting from, you may blow past the available precision of floating point (about 15 digits), and then you get a warning, like:
You have: lightyear
You want: mile;100 inch;10 inch;mm;micron
5.8786254e+12 mile + 390 * 100 inch (at 15-digit precision limit)
๐ Cooking Measure ๐
in North America, cooking recipes usually measure ingredients by volume, and use units that aren't always convenient multiples of each other ๐ญ. suppose you've got a recipe for 6 and you want to make a portion for 1. if the recipe calls for 2 1/2 cups of an ingredient, you might want to know that in terms of the measuring devices you actually own โ so you could use units and enter:
You have: (2+1|2) cup / 6
You want: cup;1|2 cup;1|3 cup;1|4 cup;tbsp;tsp;1|2 tsp;1|4 tsp
1|3 cup + 1 tbsp + 1 tsp
by default, if a unit in a list begins with a fraction of the form 1|x and its multiplier is an integer, the fraction is given as the product of the multiplier and the numerator. for example:
You have: 12.28125 ft
You want: ft;in;1|8 in;
12 ft + 3 in + 3|8 in
in lots of cases, like the one above, that's exactly what you want โ but sometimes it is not. for example, a cooking recipe for 6 might call for 5 1/4 cup of an ingredient, but you want a portion for 2, and your 1-cup measure isn't available. you might try:
You have: (5+1|4) cup / 3
You want: 1|2 cup;1|3 cup;1|4 cup
3|2 cup + 1|4 cup
and honestly that result might be totally fine for a baker who has a 1 1/2-cup measure (and recognizes the equivalence), but it may not be as useful to someone with a more limited set of measures, who does want to do extra calculations, and only wants to know <em>"How many 1/2-cup measures do I need to add?"</em> โ because after all, that's what was actually asked ๐
. with the โ--show-factorโ option, the factor won't be combined with a unity numerator, so you get:
You have: (5+1|4) cup / 3
You want: 1|2 cup;1|3 cup;1|4 cup
3 * 1|2 cup + 1|4 cup
but a user-specified fractional unit with a numerator other than 1 is never overridden โ if a unit list specifies โ3|4 cup;1|2 cupโ, a result equivalent to 1 1/2 cups will always be shown as โ2 * 3|4 cupโ whether or not the โ--show-factorโ option is given.
๐ Unit List Aliases ๐
a unit list like
cup;1|2 cup;1|3 cup;1|4 cup;tbsp;tsp;1|2 tsp;1|4 tsp
can be <em>so</em> tedious to type out ๐ฎโ๐จ. so the units program gives you shorthand names for some common combinations:
hmsโ time: hours, minutes, secondsdmsโ angle: degrees, minutes, secondstimeโ time: years, days, hours, minutes and secondsusvolโ US cooking volume: cups and smalleruswtโ US weight: pounds and ouncesftinโ length: feet, inches and 1/8 inchesftin2โ length: feet, inches and 1/2 inchesftin4โ length: feet, inches and 1/4 inchesftin8โ length: feet, inches and 1/8 inchesftin16โ length: feet, inches and 1/16 inchesftin32โ length: feet, inches and 1/32 inchesftin64โ length: feet, inches and 1/64 inchesinchfineโ length: inches subdivided to 1/64 inch
using these shorthands โ aka unit list aliases โ you can do conversions like:
You have: anomalisticyear
You want: time
1 year + 25 min + 3.4653216 sec
You have: 1|6 cup
You want: usvol
2 tbsp + 2 tsp
suppose you want to drill a clearance hole for a #10 screw and have about 1/64 inch of clearance; you could try:
You have: screwgauge(10) + 1|64 in
You want: ftin64
13.16 * 1|64 in
You have: _
You want: ftin32
6.58 * 1|32 in
if a slightly tight fit is acceptable, a 13/64-inch drill would do the job; if not, a 7/32-inch drill would work with a slightly looser fit. ๐ฅ
you can define your own unit list aliases too โ see Defining Unit List Aliases.
important: you cannot combine a unit list alias with other units. it has to appear <em>alone</em> at the โYou want:โ prompt.
you can display the definition of a unit list alias by entering it at the โYou have:โ prompt:
You have: dms
Definition: unit list, deg;arcmin;arcsec
when you specify compact output with โ--compactโ, โ--terseโ or โ-tโ and convert to a unit list, units lists the conversion factors for each unit in the list, separated by semicolons:
You have: year
You want: day;min;sec
365;348;45.974678
and unlike the case of regular output, zeros are included in this output list:
You have: liter
You want: cup;1|2 cup;1|4 cup;tbsp
4;0;0;3.6280454
ALTERNATIVE UNIT SYSTEMS ๐
okay bestie, SI is NOT the only game in town. Let's talk alternatives. ๐
CGS Units ๐ซ
So the SI is really just an extension of the older MKS (meterโkilogramโsecond) system, and it's basically eaten the older CGS (centimeterโgramโsecond) system alive โ but CGS is still living its best life in a few specialized fields, especially physics, where it gives you a way more elegant formulation of Maxwell's equations. โจ
Conversions between SI and CGS involving mechanical units? Super straightforward, it's all just powers of 10 (like, 1 m = 100 cm, easy). But conversions involving electromagnetic units are messier, and units supports four different CGS systems:
- electrostatic units (ESU)
- electromagnetic units (EMU)
- the Gaussian system
- the HeavisideโLorentz system
The tea โ on why they're different: each one made different choices for the proportionality constants in electromagnetic equations.
Coulomb's law gives you the electrostatic force between two charges separated by a distance delim $$ r:
F = k_C q_1 q_2 / r^2.
Ampere's law gives you the electromagnetic force per unit length between two current-carrying conductors separated by a distance r:
F/l = 2 k_A I_1 I_2 / r.
And those two constants, k_C and k_A, are related by the square of the speed of light: k_A = k_C / c^2. ๐
In the SI, the constants have dimensions, and there's an extra base unit โ the ampere โ that measures electric current. The CGS systems do NOT define new base units. Instead they express charge and current as derived units in terms of mass, length, and time. So:
- In the ESU system, the constant for Coulomb's law is chosen to be unity and dimensionless, which defines the unit of charge.
- In the EMU system, the constant for Ampere's law is chosen to be unity and dimensionless, which defines a unit of current.
- The Gaussian system usually uses the ESU units for charge and current; it chooses another constant so that the units for the electric and magnetic fields are the same.
- The HeavisideโLorentz system is "rationalized" so that factors of
4{pi}do not appear in Maxwell's equations. The SI system is similarly rationalized, but the other CGS systems are not. In the HeavisideโLorentz (HLU) system the factor of4{pi}appears in Coulomb's law instead; this system differs from the Gaussian system by factors of the square root of4{pi}.
The dimensions of electrical quantities in the various CGS systems are different from the SI dimensions for the same units. Strictly speaking? Conversions between these systems and SI are not possible. ๐ญ But units in different systems relate to the same physical quantities, so there IS a correspondence between them. The units program defines the units so you can convert between corresponding units in the various systems.
Here's the messy part: the CGS definitions involve cm^(1/2) and g^(1/2), which is a whole problem because units doesn't normally support fractional roots of base units. So the --units (-u) option lets you pick a CGS unit system and works around this by introducing base units for the square roots of length and mass: sqrt_cm and sqrt_g. ๐ The centimeter then becomes sqrt_cm^2 and the gram becomes sqrt_g^2. That way you can work from equations using the units in the CGS system, and enforce dimensional conformity within that system.
Recognized CGS arguments to the --units option are:
gauss[ian]esuemulhu
and the argument is case insensitive. You can also give si, which just enforces the default SI mode and displays (SI) at the You have: prompt to emphasize the units mode. Some other types of units are also supported as described below. If you give an unrecognized system, you get a warning, and units uses SI units.
The changes resulting from the--unitsoption are actually controlled by theUNITS_SYSTEMenvironment variable. ๐
If you frequently work with one of the supported CGS units systems, you may set this environment variable rather than giving the --units option at each invocation. And as usual, an option given on the command line overrides the setting of the environment variable. For example, if you'd normally work with Gaussian units but might occasionally work with SI, you could set UNITS_SYSTEM to gaussian and specify SI with the --units option.
โ ๏ธ BUT. Unlike the argument to the--unitsoption, the value ofUNITS_SYSTEMis case sensitive. So setting a value ofEMUwill have no effect other than to give an error message and set SI units. not me making that mistake ๐
The CGS definitions appear as conditional settings in the standard units data file, which you can consult for more information on how these units are defined, or on how to define an alternate units system.
The four systems, one by one ๐ซถ
ESU derives the electromagnetic units from its unit of charge, the statcoulomb, which is defined from Coulomb's law. The statcoulomb equals dyne^(1/2) cm, or cm^(3/2) g^(1/2) s^(โ1). The unit of current, the statampere, is statcoulomb sec, analogous to the relationship in SI. Other electrical units are then derived in a manner similar to that for SI units; the units use the SI names prefixed by stat-, e.g., statvolt or statV. The prefix st- is also recognized (e.g., stV).
EMU derives the electromagnetic units from its unit of current, the abampere, which is defined in terms of Ampere's law. The abampere is equal to dyne^(1/2), or cm^(1/2) g^(1/2) s^(โ1). delim off The unit of charge, the abcoulomb, is abampere sec, again analogous to the SI relationship. Other electrical units are then derived in a manner similar to that for SI units; the units use the SI names prefixed by ab-, e.g., abvolt or abV. The magnetic field units include the gauss, the oersted and the maxwell.
Gaussian โ which was also known as the Symmetric System โ uses the same charge and current units as the ESU system (e.g., statC, statA); it differs by defining the magnetic field so that it has the same units as the electric field. The resulting magnetic field units are the same ones used in the EMU system: the gauss, the oersted and the maxwell.
HeavisideโLorentz appears to lack named units. So we define five basic units โ hlu_charge, hlu_current, hlu_volt, hlu_efield and hlu_bfield โ for conversions with this system.
๐ IMPORTANT: with all of the CGS systems, the units may look the same but mean something different. The HLU system and Gaussian systems both measure magnetic field using the same CGS dimensions, but the amount of magnetic field with the same units is different in the two systems.
The CGS systems define units that measure the same thing but may have conflicting dimensions. Furthermore, the dimensions of the electromagnetic CGS units are never compatible with SI. But if you measure charge in two different systems you have measured the same physical thing, so there's a correspondence between the units in the different systems, and units supports conversions between corresponding units. ๐ฅ
- When running with SI,
unitsdefines all of the CGS units in terms of SI. - When you select a CGS system,
unitsdefines the SI units and the other CGS system units in terms of the system you have selected.
Let's see it in action:
(Gaussian) You have: statA
You want: abA
* 3.335641e-11
/ 2.9979246e+10
(Gaussian) You have: abA
You want: sqrt(dyne)
conformability error
2.9979246e+10 sqrt_cm^3 sqrt_g / s^2
1 sqrt_cm sqrt_g / s
In the above example, units converts between the current units statA and abA even though the abA, from the EMU system, has incompatible dimensions. This works because in Gaussian mode, the abA is defined in terms of the statA, so it does not have the correct definition for EMU; consequently, you cannot convert the abA to its EMU definition.
One challenge of conversion is that because the CGS system has fewer base units, quantities that have different dimensions in SI may have the same dimension in a CGS system. And yet, they may not have the same conversion factor. For example, the unit for the E field and B fields are the same in the Gaussian system, but the conversion factors to SI are quite different. This means that correct conversion is only possible if you keep track of what quantity is being measured. You cannot convert statV/cm to SI without indicating which type of field the unit measures. ๐ค
To aid in dimensional analysis, units defines various dimension units such as LENGTH, TIME, and CHARGE to be the appropriate dimension in SI. The electromagnetic dimensions such as B_FIELD or E_FIELD may be useful aids both for conversion and dimensional analysis in CGS. You can convert them to or from CGS in order to perform SI conversions that in some cases will not work directly due to dimensional incompatibilities.
This example shows how the Gaussian system uses the same units for all of the fields, but they all have different conversion factors with SI:
(Gaussian) You have: statV/cm
You want: E_FIELD
* 29979.246
/ 3.335641e-05
(Gaussian) You have: statV/cm
You want: B_FIELD
* 0.0001
/ 10000
(Gaussian) You have: statV/cm
You want: H_FIELD
* 79.577472
/ 0.012566371
(Gaussian) You have: statV/cm
You want: D_FIELD
* 2.6544187e-07
/ 3767303.1
The next example shows that the oersted cannot be converted directly to the SI unit of magnetic field, A/m, because the dimensions conflict. We cannot redefine the ampere to make this work because then it would not convert with the statampere. But you can still do this conversion as shown below. ๐
(Gaussian) You have: oersted
You want: A/m
conformability error
1 sqrt_g / s sqrt_cm
29979246 sqrt_cm sqrt_g / s^2
(Gaussian) You have: oersted
You want: H_FIELD
* 79.577472
/ 0.012566371
Natural Units ๐
Like the CGS units, "natural" units are an alternative to the SI system used primarily by physicists in different fields, with different systems tailored to different fields of study. These systems are "natural" because the base measurements are defined using physical constants instead of arbitrary values such as the meter or second. In different branches of physics, different physical constants are more fundamental, which has given rise to a variety of incompatible natural unit systems. ๐ฆ
The supported systems are the โnaturalโ units (which honestly seem to have no better name, that's just what everyone calls them ๐) used in high energy physics and cosmology, the Planck units, often used by scientists working with gravity, and the Hartree atomic units, favored by the physical chemistry and condensed matter physics girlies ๐ .
You can select the various natural units using the --units option in the same way that you select the CGS units. The โnaturalโ units come in two types: a rationalized system derived from the HeavisideโLorentz units, and an unrationalized system derived from the Gaussian system. You select these using natural and natural-gauss respectively. For conversions in SI mode, several unit names starting with natural are available. This โnaturalโ system is defined by setting {hbar}, c and the Boltzman constant to 1. Only a single base unit remains: the electron volt โจ.
The Planck units exist in a variety of forms, and units supports two. Both supported forms are rationalized, meaning factors of 4{pi} do <em>not</em> appear in Maxwell's equations. But Planck units can also differ based on how the gravitational constant is treated. This system is similar to the natural units in that c, {hbar}, and Boltzman's constant are set to 1, but here Newton's gravitational constant, G, is also fixed. In the โreducedโ Planck system, delim $$ 8{pi}G = 1 whereas in the unreduced system G = 1. The reduced system eliminates factors of 8{pi} delim off from the Einstein field equations for gravitation, so it's giving very much the same energy as the process of forming rationalized units to simplify Maxwell's equations ๐ซถ. To obtain the unreduced system use the name planck, and for the reduced Planck units, planck-red. Units such as planckenergy and planckenergy_red enable you to convert the unreduced and reduced Planck energy unit in SI mode between the various systems. In Planck units, all measurements are dimensionless.
The final natural unit system is the Hartree atomic units. Like the Planck units, all measurements in the Hartree units are dimensionless, but this system is defined from completely different physical constants: the electron mass, Planck's constant, the electron charge, and the Coulomb constant are the defining physical quantities, which are all set to unity. To invoke this system with the --units option, use the name hartree.
๐ Prompt Prefix ๐
If a unit system is specified with the --units option, the selected system's name gets prepended to the You have: prompt as a lil reminder, e.g.,
(Gaussian) You have: stC
You want:
Definition: statcoulomb = sqrt(dyne) cm = 1 sqrt_cm^3 sqrt_g / s
You can suppress that prefix by including a line
!prompt
with no argument in a site or personal units data file. And you can suppress it conditionally by including such a line within !var ... !endvar constructs, e.g.,
!var UNITS_SYSTEM gaussian gauss
!prompt
!endvar
This might be the move if you normally use Gaussian units and find the prefix distracting, but still want to be reminded when you've selected a different CGS system ๐
๐ LOGGING CALCULATIONS ๐
The --log option lets you save the results of calculations in a file, which is highkey useful if you need a permanent record of your work. For example, the fluid-flow conversion in Complicated Unit Expressions is <em>lengthy</em>, and if you were using it in designing a piping system, you might want a record of it for the project file. If the interactive session
# Conversion factor A1 for pressure drop
# dP = A1 rho f L Q^2/d^5
You have: (8/pi^2) (lbm/ft^3)ft(ft^3/s)^2(1/in^5) # Input units
You want: psi
* 43.533969
/ 0.022970568
were logged, the log file would contain
### Log started Fri Oct 02 15:55:35 2015
# Conversion factor A1 for pressure drop
# dP = A1 rho f L Q^2/d^5
From: (8/pi^2) (lbm/ft^3)ft(ft^3/s)^2(1/in^5) # Input units
To: psi
* 43.533969
/ 0.022970568
The time is written to the log file when the file is opened โฐ.
The use of comments can help clarify the meaning of calculations for the log. The log includes conformability errors between the units at the You have: and You want: prompts, but not other errors, including lack of conformability of items in sums or differences or among items in a unit list. For example, a conversion between zenith angle and elevation angle could involve
You have: 90 deg - (5 deg + 22 min + 9 sec)
^
Invalid sum or difference of non-conformable units
You have: 90 deg - (5 deg + 22 arcmin + 9 arcsec)
You want: dms
84 deg + 37 arcmin + 51 arcsec
You have: _
You want: deg
* 84.630833
/ 0.011816024
You have:
The log file would contain
From: 90 deg - (5 deg + 22 arcmin + 9 arcsec)
To: deg;arcmin;arcsec
84 deg + 37 arcmin + 51 arcsec
From: _
To: deg
* 84.630833
/ 0.011816024
The initial entry error (forgetting that minutes have dimension of time, and that arcminutes must be used for dimensions of angle โ classic mix-up, no shade ๐ญ) does <em>not</em> appear in the output. When converting to a unit list alias, units expands the alias in the log file.
The From: and To: tags are written to the log file even if the --quiet option is given. If the log file exists when units is invoked, the new results are appended to the log file. The time is written to the log file each time the file is opened. The --log option is ignored when units is used non-interactively.
๐ฆ INVOKING UNITS ๐ฆ
You invoke units like this:
units [options] [from-unit [to-unit]]
If the from-unit and to-unit are omitted, the program will use interactive prompts to determine which conversions to perform. See Interactive Use. If <em>both</em> from-unit and to-unit are given, units will print the result of that single conversion and then exit. If <em>only* from-unit appears on the command line, units will display the definition of that unit and exit. Units specified on the command line may need to be quoted to protect them from shell interpretation and to group them into two arguments. Note also that the --quiet option is enabled by default if you specify from-unit on the command line. See Command Line Use.
The default behavior of units can be changed by various options given on the command line. In most cases, the options may be given in either short form (a single - followed by a single character) or long form (-- followed by a word or hyphen-separated words). Short-form options are cryptic but require less typing; long-form options require more typing but are more explanatory and may be more mnemonic. With long-form options you need only enter sufficient characters to uniquely identify the option to the program. For example, --out %f works, but --o %f fails because units has other long options beginning with o. However, --q works because --quiet is the only long option beginning with q โจ.
Some options require arguments to specify a value (e.g., -d 12 or --digits 12). Short-form options that do not take arguments may be concatenated (e.g., -erS is equivalent to -e -r -S); the last option in such a list may be one that takes an argument (e.g., -ed 12). With short-form options, the space between an option and its argument is optional (e.g., -d12 is equivalent to -d 12). Long-form options may not be concatenated, and the space between a long-form option and its argument is <em>required</em>. Short-form and long-form options may be intermixed on the command line. Options may be given in any order, but when incompatible options (e.g., --output-format and --exponential) are given in combination, behavior is controlled by the last option given. For example, -o%.12f -e gives exponential format with the default eight significant digits).
Many options can be set interactively; this can be especially helpful for Windows users who start units from a shortcut. See Setting Options Interactively for more info.
The following options are available:
-c,--checkโ Checks that all units and prefixes defined in units data files reduce to primitive units ๐ . Displays a list of all units that cannot be reduced and a list of units with circular definitions. Also displays some other diagnostics about suspicious definitions in the units data file. Only definitions active in the current locale are checked. You should <em>always</em> run units with this option after modifying a units data file.
Some errors may hide other errors, so you should run units with this option again after correcting any errors, and keep doing so until there are no errors ๐.
--check-verbose,--verbose-checkโ Like the--checkoption, this option displays a list of units that cannot be reduced. But it <em>also</em> lists the units as they are checked. Because the--checkoption now catches circular unit definitions that previously caused units to hang, this option is no longer necessary. It is retained only for compatibility with previous versions ๐.--list-unitsโ This option displays a list of all units and exits. With output redirected to a file, it can produce a list of all units in the database, which may comprise multiple units data files. It can also be useful if you aren't sure of the name of a unit, or want to find all units of a particular type and you want a more advanced search than is available with the interactive search command. See Finding Units for some examples of how this option can be used ๐.-d ndigits,--digits ndigitsโ ok so this sets the number of significant digits in your output, and the value you give has to be greater than zero bestie, no zero, no negatives. Like-d 12means 12 sig digits, periodt. When you're in exponential output, units puts one digit to the left of the decimal point and eleven digits to the right. On most systems, the max number of internally meaningful digits is 15; ask for more than your system's max and units will throw a warning and set it to the largest meaningful value instead ๐. Want the max directly? Hand itmaxas the argument (so-d max). And just so we're clear โ "significant" here refers only to how the number is displayed ๐ ; if results depend on physical constants that aren't known to that precision, the physically meaningful precision may be less than what you see. Also,--digitsis incompatible with--output-format; give them both and the format is controlled by whichever you gave last.-e,--exponentialโ flips the numeric output format to exponential (i.e., scientific notation), just like the classic Unix units program does โจ. Default precision is eight significant digits (that's seven digits to the right of the decimal point), and you can change that with--digits. Same drama as above:--exponentialis incompatible with--output-format, and if you give both, the last option given controls the format.-o format,--output-format formatโ okay this one is the main character of output control ๐. You get complete control over the numeric output format by passing aformat. That format is a single floating point numeric format for theprintffunction in C. Every compiler supports the format typesgandG(significant digits),eandE(scientific notation), andf(fixed-point decimal). The ISO C99 standard introducedFfor fixed-point decimal plusaandAfor hexadecimal floating point โ those are allowed on compilers that support them. Default format is%.8g; want more precision? You could specify-o %.15g๐ธ. Unlike--digits, you can specify any precision you want, though ngl not all digits may be meaningful. See Numeric Output Format and the documentation forprintffor the detailed descriptions of the format specification. This option gives the greatest control over the output appearance, but it needs at least rudimentary knowledge of theprintfformat syntax. If you can't be bothered withprintfsyntax, you can get more precision more simply with--digitsor pick exponential format with--exponential. And yep โ--output-formatis incompatible with--exponentialand--digits; give either in combo with--output-formatand the last option given controls the format.-f filename,--file filenameโ tells units to load the units filefilename. You can stack up to 25 units files on the command line. Heads up though: when you use this option, units loads only the files you list on the command line โ it will not load the standard file or your personal units file unless you explicitly list them. Iffilenameis the empty string (-f ""), the default main units file (or the one specified byUNITSFILE) gets loaded in addition to any others you named with-f๐ซถ.-L logfile,--log logfileโ saves the results of your calculations into the filelogfile; this one's a whole vibe if it matters to keep a record of unit conversions or other calcs you're gonna use extensively or in something critical like a program or a design project. Iflogfileexists, the new results get appended to the file. Just so you know, this option is ignored when units is used non-interactively. See Logging Calculations for a more detailed description and some examples โจ.-H filename,--history filenameโ tells units to save history tofilename, so a record of your commands is available for retrieval across different units invocations ๐. Wanna stop the history from being saved? Setfilenameto the empty string (-H ""). This option has no effect if readline isn't available.-h,--helpโ prints out a summary of the options for units. classic ๐-m,--minusโ makes-get interpreted as a subtraction operator. This is the default behavior, so honestly it's just confirming the vibe.-p,--productโ makes-get interpreted as a multiplication operator when it has two operands. With only one operand, it acts as a negation operator:(-3). By default-is treated as subtraction, so this one's a switch-up.--oldstarโ makes*have the old-style precedence, higher than the precedence of division, so1/2*3will equal1/6.--newstarโ forces*to have the new (default) precedence that follows the usual rules of algebra:*has the same precedence as/, so1/2*3will equal3/2.-r,--roundโ when converting to a combination of units given by a unit list, this rounds the value of the last unit in the list to the nearest integer.-S,--show-factorโ when converting to a combination of units specified in a list, always show a non-unity factor before a unit that begins with a fraction with a unity denominator. By default, if the unit in a list begins with a fraction of the form1|xand its multiplier is an integer other than 1, the fraction is given as the product of the multiplier and the numerator (e.g.,3|8 inrather than3 * 1|8 in). In some cases that's not what's wanted; for example, results for a cooking recipe might show3 * 1|2 cupas3|2 cup. With--show-factor, a result equivalent to 1.5 cups will display as3 * 1|2 cuprather than3|2 cup. A user-specified fractional unit with a numerator other than 1 is never overridden, though โ if a unit list specifies3|4 cup;1|2 cup, a result equivalent to 1 1/2 cups will always be shown as2 * 3|4 cup, whether or not--show-factoris given.--conformableโ in non-interactive mode, shows all units conformable with the original unit expression. Only one unit expression is allowed; give more than one and units will exit with an error message and return failure.-v,--verboseโ gives slightly more verbose output when converting units. Combined with-cit gives the same effect as--check-verbose. Combined with--versionit produces more detailed output, equivalent to the--infooption.-V,--versionโ prints the program version number, tells you whether the readline library has been included, tells you whether UTF-8 support has been included; gives the locale, the location of the default main units data file, and the location of the personal units data file; and indicates if the personal units data file does not exist.
Given in combination with --terse, the program prints only the version number and exits.
Given in combination with --verbose, the --version option has the same effect as the --info option below.
-I,--infoโ prints the info given with--version, shows the pathname of the units program, shows the status of theUNITSFILEandMYUNITSFILEenvironment variables, plus additional info about how units locates the related files. On systems running Microsoft Windows, the status of theUNITSLOCALEenvironment variable and info about the related locale map are also given. This option is usually only interesting to developers and administrators, but sometimes it's useful for troubleshooting ๐.
Combining --version and --verbose has the same effect as giving --info.
-U,--unitsfileโ prints the location of the default main units data file and exits; if the file can't be found, it prints "Units data file not found".-u units-system,--units units-systemโ specify a CGS units system or natural units system. The supported units systems are:gauss[ian],esu,emu,hlu,natural,natural-gauss,hartree,planck,planck-red, andsi. See Alternative Unit Systems for further info on these ๐ซ.-l locale,--locale localeโ forces a specified locale likeen_GBto get British definitions by default. This overrides the locale determined from system settings or environment variables. See Locale for a description of the locale format.-n,--nolistsโ disables conversion to unit lists.-s,--strictโ suppresses conversion of units to their reciprocal units. For example, units will normally convert hertz to seconds because those units are reciprocals of each other. The strict option requires that units be strictly conformable to perform a conversion, and will give an error if you try to convert hertz to seconds.-1,--one-lineโ gives only one line of output (the forward conversion); does not print the reverse conversion. If a reciprocal conversion is performed, units will still print the "reciprocal conversion" line.-t,--terseโ prints just one conversion factor, zero clutter, no vibes, no decoration. And if you're asking for a definition instead, it prints just the definition (units included, bestie). This is THE option for when you're callingunitsfrom inside another program and you need output that's easy to parse. Like,units --terse mile mgives you exactly1690.344. Nothing else. Periodt. This one option is secretly the combined effect of all of these:--strict,--quiet,--one-line,--compact. And when you pair it with--version? It shows you only the program name and version number. Minimalist queen. ๐--compactโ compact output that features only the conversion factor ๐ . The multiplication and division signs? Gone. Leading whitespace? Never heard of her. If you convert to a unit list, the output is a semicolon separated list of factors. Heads up tho: this turns off the--verboseoption. ๐ซถ-q,--quiet,--silentโ suppresses the display of statistics about how many units got loaded, any messages printed by the units database, and the prompting of the user for units. It does not change howunitsdisplays its results โ that's a whole different thing, don't get it twisted. And plot twist: this option is turned on by default if you invokeunitswith a unit expression on the command line. ๐
โจ SETTING OPTIONS INTERACTIVELY โจ
Okay so here's the tea: a ton of those command-line options can also be set interactively, which means you don't have to quit and restart units just to change a value. Lifesaver. This is lowkey especially helpful for Windows girlies who start units from a shortcut. ๐ช
Type set and you get a list of every option you can set interactively, plus the current and possible values. Any option that's set to something other than its default gets an asterisk (*) stuck in front of it. Like, for example:
You have: set
q[uiet] = no (y|n) do/donโt suppress prompting
o[neline] = no (y|n) do/donโt suppress the second line of output
st[rict] = no (y|n) do/donโt suppress reciprocal unit conversion
(e.g., Hz<->s)
t[erse] = no (y|n) do/donโt give very terse output
c[ompact] = no (y|n) do/donโt suppress printing tab, SETFLAG, and โ/โ
characters in results
v[erbose] = 1 (0|1|2) amount of information shown
*d[igits] = 9 number of significant digits in output
e[xponential] = no (y|n) do/donโt use exponential ("scientific") notation
*f[ormat] = %.9g printf(3) format specification
u[nitlists] = yes (y|n) do/donโt allow conversion to unit lists
r[ound] = no (y|n) do/donโt round last element of unit list output
to an integer
sh[owfactor] = no (y|n) do/donโt show non-unity factor before 1|x
in multi-unit output
The characters inside the square brackets are optional, so you can change a setting by typing only one or two characters. Slay, efficiency. ๐
The syntax for setting options is set option = value; and the spaces around the = sign are optional.
Some settings are Boolean โ enabled by entering yes (or just y) and disabled by entering no (or just n). For example:
You have: set quiet = y
quiet = yes
Other settings take an integer value; for example:
You have: set d=11
digits = 11
format = %.11g
The format setting takes a string โ specifically, the format specification for the printf function in the C programming language. For example:
You have: set format = %.9g
format = %.9g
And typing set option shows you the current value of that option, for example:
You have: set u
unitlists = yes
You have: set d
digits = 8
format = %.8g
For the digits and exponential options, the value of format gets shown too. ๐
๐ SCRIPTING WITH UNITS ๐
Okay bestie, real talk: despite its numerous options, units cannot cover every conceivable unit-conversion task. It's not a mind reader. ๐ญ
Say we found some mysterious scale but we cannot figure out the units it's reporting in. We reach into our pocket, place a 3.75-gram coin on the scale, and observe the scale reading 0.120. How do we quickly determine the units? Or โ different scenario โ maybe we're wondering if a unit has any "synonyms," i.e., other units with the same value.
Good news: the capabilities of units are easily extended with simple scripting. ๐ง Both of those questions involve conformable units; on a system with Unix-like utilities, conversions to conformable units could be shown accomplished with the following script:
#!/bin/sh
progname=`basename $0 .sh`
umsg="Usage: $progname [<number>] unit"
if [ $# -lt 1 ]
then
echo "$progname: missing quantity to convert"
echo "$umsg"
exit 1
fi
for unit in `units --conformable "$*" | cut -f 1 -d ' '`
do
echo "$*" # have -- quantity to convert
echo $unit # want -- conformable unit
done | units --terse --verbose
When units is invoked with no non-option arguments, it reads have/want pairs โ on alternating lines โ from its standard input. So the whole task can be accomplished with only two invocations of units. Why does that matter? Because it avoids the computational overhead of needlessly reprocessing the units database for each conformable unit, plus the inherent system overhead of process invocation. Main character efficiency. โญ
By itself, the script is not very useful. But it could be used in combination with other commands to address specific tasks. For example, running the script through a simple output filter could help solve the scale problem above. If the script is named conformable, running
$ conformable 3.75g | grep 0.120
gives
3.75g = 0.1205653 apounce
3.75g = 0.1205653 fineounce
3.75g = 0.1205653 ozt
3.75g = 0.1205653 tradewukiyeh
3.75g = 0.1205653 troyounce
So we might conclude that the scale is calibrated in troy ounces. Mystery solved, detective era. ๐ต๏ธโโ๏ธ
We might run
$ units --verbose are
Definition: 100 m^2 = 100 m^2
and wonder if are has any synonyms, value. To find out, we could run
$ conformable are | grep "= 1 "
are = 1 a
are = 1 are
๐ OUTPUT STYLES ๐
The output can be tweaked in various ways using command line options. With no options, the output looks like this:
$ units
Currency exchange rates from FloatRates (USD base) on 2023-07-08
3612 units, 109 prefixes, 122 nonlinear units
You have: 23ft
You want: m
* 7.0104
/ 0.14264521
You have: m
You want: ft;in
3 ft + 3.3700787 in
ngl, this is arguably a bit cryptic ๐
โ the --verbose option makes clear what the output actually means:
$ units --verbose
Currency exchange rates from FloatRates (USD base) on 2023-07-08
3612 units, 109 prefixes, 122 nonlinear units
You have: 23 ft
You want: m
23 ft = 7.0104 m
23 ft = (1 / 0.14264521) m
You have: meter
You want: ft;in
meter = 3 ft + 3.3700787 in
The --quiet option suppresses the clutter displayed when units starts, plus the prompts to the user. And remember โ this option is enabled by default when you give units on the command line. ๐ซถ
$ units --quiet
23 ft
m
* 7.0104
/ 0.14264521
$ units 23ft m
* 7.0104
/ 0.14264521
The remaining style options let you display only numerical values without the tab or the multiplication and division signs, or display just a single line showing the forward conversion:
$ units --compact 23ft m
7.0104
0.14264521
$ units --compact m 'ft;in'
3;3.3700787
$ units --one-line 23ft m
* 7.0104
$ units --one-line 23ft 1/m
reciprocal conversion
* 0.14264521
$ units --one-line 23ft kg
conformability error
7.0104 m
1 kg
Note that when converting to a unit list, the--compactoption displays a semicolon separated list of results. Also be aware that theone-lineoption doesn't live up to its name if you execute a reciprocal conversion or if you get a conformability error. ๐ The former case can be prevented using the--strictoption, which suppresses reciprocal conversions. Similarly you can suppress unit list conversion using--nolists. It is impossible to prevent the three line error output.
$ units --compact --nolists m 'ft;in'
Error in 'ft;in': Parse error
$ units --one-line --strict 23ft 1/m
The various style options can be combined appropriately. And the ultimate combination is the --terse option, which combines --strict, --quiet, --one-line, and --compact to produce the minimal output โ just a single number for regular conversions, and a semicolon separated list for conversion to unit lists. This will likely be the best choice for programs that want to call units and then process its result. Iconic behavior, honestly. ๐
$ units --terse 23ft m
7.0104
$ units --terse m 'ft;in'
3;3.3700787
$ units --terse 23ft 1/m
conformability error
7.0104 m
1 / m
$ units --terse '1 mile'
1609.344 m
$ units --terse mile
5280 ft = 1609.344 m
๐ธ ADDING YOUR OWN DEFINITIONS ๐ธ
๐ Units Data Files ๐
The units and prefixes that units can convert are defined in the units data file โ typically /usr/share/units/definitions.units. If you can't find this file, run units --version to get information on the file locations for your installation. ๐
So you can extend or modify this data file if you have the appropriate user privileges โ but it's usually better to put extensions in separate files so that the definitions will be preserved if you update units. Future-you says thank you. ๐
You can include additional data files in the units database using the !include command in the standard units data file. For example
!include /usr/local/share/units/local.units
might be appropriate for a site-wide supplemental data file.
The location of the!includestatement in the standard units data file is important โ later definitions replace earlier ones, so any definitions in an included file will override definitions before the!includestatement in the standard units data file.
With normal invocation, no warning is given about redefinitions. So to make sure you don't have an unintended redefinition, run units -c after making changes to any units data file. Do it, bestie, don't skip it. โจ
okay so bestie, you wanna add your own units on top of (or instead of) the standard or site-wide supplemental units data files? say less ๐
you can just drop them in the .units file in your home directory. If that file exists, it gets read after the standard units data file โ so anything you define in there replaces definitions of the same units from the standard data file, or from files included by the standard data file. Periodt.
heads up though: this personal file will not be read if you specify any units files on the command line. (Under Windows the personal units file is named unitdef.units.) And if you're ever like "where even is my personal units file??" โ running units -V will display its location and name. ๐ซถ
The units program first tries to figure out your home directory from the HOME environment variable. On systems running Microsoft Windows, if HOME doesn't exist, units attempts to find your home directory from HOMEDRIVE, HOMEPATH and USERPROFILE. And you can specify an arbitrary file as your personal units data file with the MYUNITSFILE environment variable โ if that variable exists, its value is used without searching your home directory at all. The default units data files are described in more detail in Data Files. โจ
๐ Defining New Units and Prefixes ๐
A unit is specified on a single line by giving its name and an equivalence. Comments start with a # character, which can appear anywhere in a line. The backslash character (\) acts as a continuation character if it appears as the last character on a line, which makes it possible to spread definitions out over several lines if you want. ๐
A file can be included by giving the command !include followed by the file's name. The ! must be the first character on the line. The file will be sought in the same directory as the parent file unless you give a full path. And ngl, the name of the file to be included cannot contain spaces or the comment character #. ๐
Unit names cannot begin or end with an underscore (_) or a decimal point (.), and cannot contain any of the operator characters +, -, *, /, |, ^, ;, ~, a comma (,), the comment character #, or parentheses. To facilitate copying and pasting from documents, several typographical characters are converted to operators: the figure dash (U+2012), minus (-; U+2212), and en dash (โ; U+2013) are converted to the operator -; the multiplication sign (ร; U+00D7), N-ary times operator (U+2A09), dot operator (โ
; U+22C5), and middle dot (ยท; U+00B7) are converted to the operator *; the division sign (รท; U+00F7) is converted to the operator /; and the fraction slash (U+2044) is converted to the operator | โ so accordingly, none of these characters can appear in unit names. ๐
Names cannot begin with a digit, and if a name ends in a digit other than zero or one, then the name must end with an underscore followed by a string consisting only of digits and decimal points. For example, foo_2, foo_3.14, and foo_3...9 are valid names but foo2 or foo_a2 are invalid. The underscore is necessary because without it, units cannot determine whether foo2 is a unit name or represents foo^2. Zero and one are exceptions because units never interprets them as exponents. ๐ง
You could define nitrous oxide as
N2O nitrogen 2 + oxygen
but would need to define nitrogen dioxide as
NO_2 nitrogen + oxygen 2
Be careful to define new units in terms of old ones so that a reduction leads to the primitive units, which are marked with ! characters. Dimensionless units are indicated by using the string !dimensionless for the unit definition. โญ
When adding new units, be sure to use the-coption to check that the new units reduce properly and that there are no circular definitions that lead to endless loops. Because some errors may hide other errors, you should rununitswith the-coption again after correcting any errors, and keep doing so until no errors are displayed. ๐ฅ
If you define any units that contain + characters in their definitions, carefully check them because the -c option will not catch non-conformable sums. Be careful with the - operator as well. When used as a binary operator, the - character can perform addition or multiplication depending on the options used to invoke units. To ensure consistent behavior use - only as a unary negation operator when writing units definitions. To multiply two units leave a space or use the * operator with care, recalling that it has two possible precedence values and may require parentheses to ensure consistent behavior. To compute the difference of foo and bar write foo+(-bar) or even foo+-bar. ๐ญ
You may wish to intentionally redefine a unit. When you do this, and use the -c option, units displays a warning message about the redefinition. You can suppress these warnings by redefining a unit using a + at the beginning of the unit name. Do not include any white space between the + and the redefined unit name. โจ
Here is an example of a short data file that defines some basic units:
m ! # The meter is a primitive unit
sec ! # The second is a primitive unit
rad !dimensionless # A dimensionless primitive unit
micro- 1e-6 # Define a prefix
minute 60 sec # A minute is 60 seconds
hour 60 min # An hour is 60 minutes
inch 72 m # Inch defined incorrectly terms of meters
ft 12 inches # The foot defined in terms of inches
mile 5280 ft # And the mile
+inch 0.0254 m # Correct redefinition, warning suppressed
A unit that ends with a - character is a prefix. If a prefix definition contains any / characters, be sure they are protected by parentheses. If you define half- 1/2, then halfmeter would be equivalent to 1 / (2 meter). ๐
๐ฆ Defining Nonlinear Units ๐ฆ
Some unit conversions of interest are nonlinear; for example, temperature conversions between the Fahrenheit and Celsius scales cannot be done by simply multiplying by conversion factors. ๐
When you give a linear unit definition such as inch 2.54 cm you are providing information that units uses to convert values in inches into primitive units of meters. For nonlinear units, you give a functional definition that provides the same information. ๐
Nonlinear units are represented using a functional notation. It is best to regard this notation not as a function call but as a way of adding units to a number, much the same way that writing a linear unit name after a number adds units to that number. Internally, nonlinear units are defined by a pair of functions that convert to and from linear units in the database, so that an eventual conversion to primitive units is possible. โจ
Here is an example nonlinear unit definition:
tempF(x) units=[1;K] domain=[-459.67,) range=[0,) \
(x+(-32)) degF + stdtemp ; (tempF+(-stdtemp))/degF + 32
A nonlinear unit definition comprises a unit name, a formal parameter name, two functions, and optional specifications for units, the domain, and the range (the domain of the inverse function). The functions tell units how to convert to and from the new unit. To produce valid results, the arguments of these functions need to have the correct dimensions and be within the domains for which the functions are defined. ๐ง
The definition begins with the unit name followed immediately (with no spaces) by a ( character. In the parentheses is the name of the formal parameter. Next is an optional specification of the units required by the functions in the definition. In the example above, the units=[1;K] specification indicates that the tempF function requires an input argument conformable with 1 (i.e., the argument is dimensionless), and that the inverse function requires an input argument conformable with K. For normal nonlinear units definition, the forward function will always take a dimensionless argument; in general, the inverse function will need units that match the quantity measured by your nonlinear unit. Specifying the units enables units to perform error checking on function arguments, and also to assign units to domain and range specifications, which are described later. ๐
Next the function definitions appear. In the example above, the tempF function is defined by
tempF(x) = (x+(-32)) degF + stdtemp
This gives a rule for converting x in the units tempF to linear units of absolute temperature, which makes it possible to convert from tempF to other units. ๐ฅ
To enable conversions to Fahrenheit, you must give a rule for the inverse conversions. The inverse will be x(tempF) and its definition appears after a ; character. In our example, the inverse is
x(tempF) = (tempF+(-stdtemp))/degF + 32
This inverse definition takes an absolute temperature as its argument and converts it to the Fahrenheit temperature. The inverse can be omitted by leaving out the ; character and the inverse definition, but then conversions to the unit will not be possible. If the inverse definition is omitted, the --check option will display a warning. It is up to you to calculate and enter the correct inverse function to obtain proper conversions; the --check option tests the inverse at one point and prints an error if it is not valid there, but this is not a guarantee that your inverse is correct. ๐
With some definitions, the units may vary. For example, the definition
square(x) x^2
can have any arbitrary units, and can also take dimensionless arguments. In such a case, you should not specify units. If a definition takes a root of its arguments, the definition is valid only for units that yield such a root. For example,
squirt(x) sqrt(x)
is valid for a dimensionless argument, and for arguments with even powers of units. ๐ธ
Some definitions may not be valid for all real numbers. In such cases, units can handle errors better if you specify an appropriate domain and range. You specify the domain and range as shown below:
baume(d) units=[1;g/cm^3] domain=[0,130.5] range=[1,10] \
(145/(145-d)) g/cm^3 ; (baume+-g/cm^3) 145 / baume
In this example the domain is specified after domain= with the two numerical endpoints given in brackets. No spaces can appear before the =. And in accord with mathematical convention (yes bestie, we're being fancy), square brackets mean a closed interval โ one that includes its endpoints โ and parentheses mean an open interval, which does not include its endpoints. An interval can be open or closed on one or both ends, and an interval that's unbounded on either end is indicated by just... omitting the limit on that end. Iconic. ๐
So for example, a quantity that decibel (dB) gets applied to can have any value greater than zero, so the range is indicated by (0,):
decibel(x) units=[1;1] range=(0,) 10^(x/10); 10 log(decibel)
If the domain or range is given, the second endpoint must be greater than the first. No cap. And the intervals given for the domain and range have to be numbers โ they cannot include units or any calculations. Sorry girl, that's just the rules. ๐ซ
The domain and range specifications can show up independently and in any order alongside the units specification. The values for the domain and range endpoints get attached to the units given in the units specification, and if necessary, the parameter value is adjusted for comparison with the endpoints. So like, if a definition includes units=[1;ft] and range=[3,), the range will be taken as 3 ft to infinity. And if the function gets passed a parameter of 900 mm, that value gets adjusted to 2.9527559 ft, which is outside the specified range. Rude, but correct. ๐ญ
If you omit the units specification from that previous example, units literally cannot tell whether you mean the lower endpoint to be 3 ft or 3 microfurlongs, and it can't adjust the parameter value of 900 mm for comparison. Without units, numerical values other than zero or plus or minus infinity for domain or range endpoints are meaningless, and accordingly they are not allowed. If you give other values without units, the definition gets ignored and you get an error message. Ignored. Deleted. Gone. ๐
Although the units, domain, and range specifications are optional, it's best to give them when they're applicable โ doing so lets units do better error checking and give more helpful error messages. Giving the domain and range also enables the --check option to find a point in the domain to use for its point check of your inverse definition. So like, do it for her. ๐ซถ
You can make synonyms for nonlinear units by providing both the forward and inverse functions; inverse functions can be obtained using the ~ operator. So to create a synonym for tempF you could write
fahrenheit(x) units=[1;K] tempF(x); ~tempF(fahrenheit)
This is useful for creating a nonlinear unit definition that differs slightly from an existing definition without having to repeat the original functions. For example,
dBW(x) units=[1;W] range=[0,) dB(x) W ; ~dB(dBW/W)
If you wish a synonym to refer to an existing nonlinear unit without modification, you can do so way more simply by adding the synonym with appended parentheses as a new unit, with the existing nonlinear unit โ without parentheses โ as the definition. So to create a synonym for tempF you could write
fahrenheit() tempF
The definition must be a nonlinear unit; for example, the synonym
fahrenheit() meter
will result in an error message when units starts. Read that again bestie, it's a whole trap. ๐
You may occasionally wish to define a function that operates on units. This can be done using a nonlinear unit definition. For example, the definition below provides conversion between radius and the area of a circle. This definition requires a length as input and produces an area as output, as indicated by the units= specification. Specifying the range as the nonnegative numbers can prevent cryptic error messages. ๐ง
circlearea(r) units=[m;m^2] range=[0,) pi r^2 ; sqrt(circlearea/pi)
โจ Defining Piecewise Linear Units โจ
Sometimes you may be interested in a piecewise linear unit, like many wire gauges. Piecewise linear units can be defined by specifying conversions to linear units on a list of points. Conversion at other points will be done by linear interpolation. A partial definition of zinc gauge is
zincgauge[in] 1 0.002, 10 0.02, 15 0.04, 19 0.06, 23 0.1
In this example, zincgauge is the name of the piecewise linear unit. The definition of such a unit is indicated by the embedded [ character. After the bracket, you should indicate the units to be attached to the numbers in the table. No spaces can appear before the ] character, so a definition like foo[kg meters] is invalid; instead write foo[kg*meters]. The definition of the unit consists of a list of pairs optionally separated by commas. This list defines a function for converting from the piecewise linear unit to linear units. The first item in each pair is the function argument; the second item is the value of the function at that argument (in the units specified in brackets).
In this example, we define zincgauge at five points. For example, we set zincgauge(1) equal to 0.002 in. Definitions like this may be more readable if written using continuation characters as
zincgauge[in] \
1 0.002 \
10 0.02 \
15 0.04 \
19 0.06 \
23 0.1
With the preceding definition, the following conversion can be performed:
You have: zincgauge(10)
You want: in
* 0.02
/ 50
You have: .01 inch
You want: zincgauge
5
If you define a piecewise linear unit that is not strictly monotonic, then the inverse will not be well defined. If the inverse is requested for such a unit, units will return the smallest inverse. Smallest inverse, not the one you wanted. That's the vibe. ๐ญ
After adding nonlinear units definitions, you should normally run units --check to check for errors. If the units keyword is not given, the --check option checks a nonlinear unit definition using a dimensionless argument, and then checks using an arbitrary combination of units, as well as the square and cube of that combination; a warning is given if any of these tests fail. For example,
Warning: function 'squirt(x)' defined as 'sqrt(x)'
failed for some test inputs:
squirt(7(kg K)^1): Unit not a root
squirt(7(kg K)^3): Unit not a root
Running units --check will print a warning if a non-monotonic piecewise linear unit is encountered. For example, the relationship between ANSI coated abrasive designation and mean particle size is non-monotonic in the vicinity of 800 grit:
ansicoated[micron] \
. . .
600 10.55 \
800 11.5 \
1000 9.5 \
Running units --check would give the error message
Table 'ansicoated' lacks unique inverse around entry 800
Although the inverse is not well defined in this region, it's not really an error. Viewing such error messages can be tedious, and if there are enough of them, they can distract from true errors. Error checking for nonlinear unit definitions can be suppressed by giving the noerror keyword; for the examples above, this could be done as
squirt(x) noerror domain=[0,) range=[0,) sqrt(x); squirt^2
ansicoated[micron] noerror \
. . .
Use thenoerrorkeyword with caution. The safest approach after adding a nonlinear unit definition is to rununits --checkand confirm that there are no actual errors before adding thenoerrorkeyword. Do not just slapnoerroron it and hope, bestie. ๐จ
๐ฆ Defining Multivariate Functions ๐ฆ
Some common dimensional calculations โ like wind chill or body mass index โ have more than one parameter. To support these calculations, units allows multivariate functions as unit definitions. Unlike the nonlinear units described above, multivariate functions provide only a forward evaluation and are not invertible: it is impossible to convert a wind chill output back to the temperature and wind speed that generated it. One-way street, periodt. ๐
A multivariate function definition is similar to that for other nonlinear units. For example, you could define bmi like this, starting with the unit's name followed immediately without white space by a comma-separated parameter list:
bmi(ht,wt) units=[m,kg] domain=(0,)(0,) (wt/kg)/(ht/m)^2
This defines a new unit, bmi, that has two parameters, height, and weight. You are allowed to use white space in the parameter list. The optional units= specification (with no space before the =) provides a comma-separated list in square brackets of units that provide the dimensions of the parameters. If you list fewer units than the number of parameters, the remaining parameters will allow any unit. For univariate nonlinear units, a semicolon introduces the units of the inverse. The semicolon is not permitted in the units= list for multivariate functions.
You specify the domain, if desired, using domain=, followed (without white space) by the intervals defining the domain of each parameter, either juxtaposed or separated by commas. The above example requires that both arguments be strictly positive. As usual, use square brackets to indicate closed intervals. The rules for domain intervals are the same as those described above for nonlinear units. If you need to indicate an unconstrained input, give the interval (,). The intervals in the domain specification must use numerical values; you cannot use units or calculations in the domain.
The final part of the definition is the expression that defines the unit. Since inverses are not well-defined for multivariate units, you cannot provide an inverse. And since you cannot provide an inverse, you also cannot provide a range, so the range= specification is invalid for multivariate functions. Invalid. Don't even try it. ๐
If you need to specify that a particular unit is of arbitrary dimension when units appearing after it in the parameter list are of specified dimension, you can do this using the special dimension specification, *. Here is a toy example:
func(a,b) units=[*,1] domain=(,),[-1,1] a asin(b)
In this example the first argument is permitted to be of any dimension, but the second argument must be dimensionless. The first argument has no domain bounds, but the second one must lie in the domain of the arcsine function. ๐
๐ Defining Unit List Aliases ๐
Unit list aliases are treated differently from unit definitions, because they are a data entry shorthand rather than a true definition for a new unit. A unit list alias definition begins with !unitlist and includes the alias and the definition; for example, the aliases included in the standard units data file are
!unitlist hms hr;min;sec
!unitlist time year;day;hr;min;sec
!unitlist dms deg;arcmin;arcsec
!unitlist ftin ft;in;1|8 in
!unitlist usvol cup;3|4 cup;2|3 cup;1|2 cup;1|3 cup;1|4 cup;\
tbsp;tsp;1|2 tsp;1|4 tsp;1|8 tsp
Shorthand queen behavior honestly. ๐
Unit list aliases are only for unit lists, so the definition has to include a ;. And bestie, they can never be combined with units or with other unit list aliases โ so that time definition up there could not have been shortened to year;day;hms. Nope. Not allowed. ๐
โโ๏ธ
As always, run units --check to make sure the units listed in your unit list aliases are conformable. Do it. It's free. ๐ซถ
โจ NUMERIC OUTPUT FORMAT โจ
By default, units shows results to eight significant digits in general number format. Cute, right? But you can absolutely switch it up with --exponential, --digits, and --output-format. ๐
--exponentialsets an exponential format (a.k.a. scientific notation) like the one in the original Unixunitsprogram.--digitslets you specify a different number of significant digits.--output-formatgives you full control over the output's appearance using the format for theprintffunction in the C programming language.
If you only wanna change the number of significant digits or specify the exponential format type, just use --digits and --exponential. Simple. Iconic. ๐ธ
But --output-format? That one affords the greatest control of the output appearance โ at the cost of requiring at least rudimentary knowledge of the printf format syntax. It's giving "worth it but do your homework." See Invoking Units for descriptions of these options. ๐
Format Specification
The format specification recognized with --output-format is a subset of the one for printf. The format specification has the form:
%[flags][width][.precision]type
It must begin with %, and it must end with a floating-point type specifier:
gorGโ specifies the number of significant digitseorEโ scientific notationfโ fixed-point decimal
The ISO C99 standard added the F type for fixed-point decimal and the a and A types for hexadecimal floating point; these types are allowed with compilers that support them. Type length modifiers (like L to indicate a long double) are inapplicable and are not allowed. ๐ซ
The default format for units is %.8g; for greater precision, you could specify -o %.15g. โจ
Now, the tea on g and G: they use exponential format whenever the exponent would be less than -4, so the value 0.000013 displays as 1.3e-005. These types also use exponential notation when the exponent is greater than or equal to the precision โ so with the default format, the value 5 ร 10^7 displays as 50000000 and the value 5 ร 10^8 displays as 5e+008. ๐ฎ
If you prefer fixed-point display, you might specify -o %.8f โ however, small numbers will display very few significant digits, and values less than 5 ร 10^-8 will show nothing but zeros. Nothing. Just zeros. ๐
The format specification may include one or more optional flags: +, (space), #, -, or 0 (the digit zero). The digit-grouping flag ' is allowed with compilers that support it. Flags are followed by an optional value for the minimum field width, and an optional precision specification that begins with a period (e.g., .6). The field width includes the digits, decimal point, the exponent, thousands separators (with the digit-grouping flag), and the sign if any of these are shown. ๐งฎ
Flags
+โ causes the output to have a sign (+or-).(space) โ similar to the+flag, except that when the value is positive, it is prefixed with a space rather than a plus sign; this flag is ignored if the+flag is also given.#โ causes the output value to contain a decimal point in all cases; by default, the output contains a decimal point only if there are digits (which can be trailing zeros) to the right of the point. With thegorGtypes, the#flag also prevents the suppression of trailing zeros.'โ the digit-grouping flag; shows a thousands separator in digits to the left of the decimal point.-โ the output value is left aligned within the specified field width.0(the digit zero) โ if a field width greater than needed to show the output value is specified, causes the output value to be left padded with zeros until the specified field width is reached. The0flag has no effect if the-(left align) flag is given.
The + or flag could be useful if conversions might include positive and negative results, and you wanted to align the decimal points in exponential notation. ๐ฏ
The digit-grouping flag ' can be useful when displaying large numbers in fixed-point decimal; for example, with the format %f,
You have: mile
You want: microfurlong
* 8000000.000000
/ 0.000000
the magnitude of the first result may not be immediately obvious without counting the digits to the left of the decimal point. ๐ตโ๐ซ If the thousands separator is the comma (,), the output with the format %'f might be
You have: mile
You want: microfurlong
* 8,000,000.000000
/ 0.000000
making the magnitude readily apparent. ๐ Unfortunately, few compilers support the digit-grouping flag. Sad. ๐ญ
And here's the 0 flag in action โ with the format %011.6f,
You have: troypound
You want: grain
* 5760.000000
/ 0000.000174
Field Width
By default, the output value is left aligned and shown with the minimum width necessary for the specified (or default) precision. If a field width greater than this is specified, the value shown is right aligned, and padded on the left with enough spaces to provide the specified field width. ๐ซง
A width specification is typically used with fixed-point decimal to have columns of numbers align at the decimal point; this arguably is less useful with units than with long columnar output, but it may nonetheless assist in quickly assessing the relative magnitudes of results. So like... it's a vibe. A useful vibe. ๐
For example, with the format %12.6f,
You have: km
You want: in
* 39370.078740
/ 0.000025
You have: km
You want: rod
* 198.838782
/ 0.005029
You have: km
You want: furlong
* 4.970970
/ 0.201168
See how everything lines up?? Chef's kiss. ๐
Precision
The meaning of "precision" depends on the format type:
- With
gorG, it specifies the number of significant digits (like the--digitsoption). - With
e,E,f, orF, it specifies the maximum number of digits to be shown after the decimal point.
With the g and G format types, trailing zeros are suppressed, so the results may sometimes have fewer digits than the specified precision (as indicated above, the # flag causes trailing zeros to be displayed). ๐
The default precision is 6, so %g is equivalent to %.6g, and would show the output to six significant digits. Similarly, %e or %f would show the output with six digits after the decimal point. Easy math, bestie. โจ
The C printf function allows a precision of arbitrary size, whether or not all of the digits are meaningful. With most compilers, the maximum internal precision with units is 15 decimal digits (or 13 hexadecimal digits). With the --digits option, you are limited to the maximum internal precision; with the --output-format option, you may specify a precision greater than this, but it may not be meaningful. โ ๏ธ
In some cases, specifying excess precision can result in rounding artifacts. Do not trust the extra digits, they are lying to you. ๐
For example, a pound is exactly 7000 grains, but with the format %.18g, the output might be
You have: pound
You want: grain
* 6999.9999999999991
/ 0.00014285714285714287
With the format %.25g you might get the following:
You have: 1/3
You want:
Definition: 0.333333333333333314829616256247
In this case the displayed value includes a series of digits that represent the underlying binary floating-point approximation to 1/3 but are not meaningful for the desired computation. ๐ญ In general, the result with excess precision is system dependent. The precision affects only the display of numbers; if a result relies on physical constants that are not known to the specified precision, the number of physically meaningful digits may be less than the number of digits shown. ๐ง
See the documentation for printf for more detailed descriptions of the format specification. ๐
Heads up bestie: the--output-formatoption is incompatible with the--exponentialor--digitsoptions; if the former is given in combination with either of the latter, the format is controlled by the last option given. Last one wins. Periodt. ๐
okay so this next bit is where units gets โจculturally awareโจ and honestly? it's giving world tour. ๐
๐ธ LOCALIZATION ๐ธ
Some units have different values in different locations. Bestie, that's just how it is. The localization feature accommodates this by letting a units data file specify definitions that depend on the user's locale. ๐
๐ Locale
A locale is a subset of a user's environment that says what language and country the user is in, plus some attendant preferences, like how dates get formatted. โจ
The units program tries to figure out the locale from the POSIX setlocale function; if that can't be done, units peeks at the environment variables LC_CTYPE and LANG. ๐
On POSIX systems, a locale looks like language_*country*, where language is the two-character code from ISO 639-1 and country is the two-character code from ISO 3166-1; language is lower case and country is upper case. For example, the POSIX locale for the United Kingdom is en_GB. ๐ฌ๐ง
On systems running Microsoft Windows, the value returned by setlocale is different from the POSIX one; units tries to map the Windows value to a POSIX value using a table in the file locale_map.txt, which lives in the same directory as the other data files. That file includes entries for many combinations of language and country, and you can extend it to include other combinations. ๐บ๏ธ
The locale_map.txt file is made of two tab-separated columns; each entry looks like
Windows-locale POSIX-locale
where POSIX-locale is as described above, and Windows-locale typically spells out both the language and country. For example, the entry for the United States is
English_United States en_US
You can force units to run in a desired locale by using the -l option. ๐ซถ
So to create unit definitions for a particular locale, you start a block of definitions in a unit datafile with !locale followed by a locale name. The ! must be the first character on the line. The units program reads the following definitions only if the current locale matches. You close the block of localized units with !endlocale. Here's an example, which defines the British gallon:
!locale en_GB
gallon 4.54609 liter
!endlocale
๐ฆ Additional Localization
Sometimes the locale just isn't enough to pin down unit preferences. ๐ญ There could be regional preferences, or a company could have its own specific preferences. Though it's probably uncommon, such differences could arise with the choice of English customary units outside of English-speaking countries. To address this, units lets you specify definitions that depend on environment variable settings. The environment variables can be controlled based on the current locale, or the user can set them to force a particular group of definitions. ๐ฅ
A conditional block of definitions in a units data file begins with either !var or !varnot followed by an environment variable name and then a space separated list of values. The leading ! must appear in the first column of a units data file, and the conditional block is terminated by !endvar.
- Definitions in blocks beginning with
!varare executed only if the environment variable is exactly equal to one of the listed values. - Definitions in blocks beginning with
!varnotare executed only if the environment variable does not equal any of the list values.
The inch has long been a customary measure of length in many places. The word comes from the Latin uncia, meaning "one twelfth," referring to its relationship with the foot. By the 20th century, the inch was officially defined in English-speaking countries relative to the yard, but until 1959, the yard differed slightly among those countries. In France the customary inch, which was displaced in 1799 by the meter, had a different length based on a french foot. ๐ฅ
These customary definitions could be accommodated as follows:
!var INCH_UNIT usa
yard 3600|3937 m
!endvar
!var INCH_UNIT canada
yard 0.9144 meter
!endvar
!var INCH_UNIT uk
yard 0.91439841 meter
!endvar
!var INCH_UNIT canada uk usa
foot 1|3 yard
inch 1|12 foot
!endvar
!var INCH_UNIT france
foot 144|443.296 m
inch 1|12 foot
line 1|12 inch
!endvar
!varnot INCH_UNIT usa uk france canada
!message Unknown value for INCH_UNIT
!endvar
When units reads the above definitions it will check the environment variable INCH_UNIT and load only the definitions for the appropriate section. If INCH_UNIT is unset or is not set to one of the four values listed, then units will run the last block. In this case that block uses the !message command to display a warning message. โ ๏ธ Alternatively that block could set default values.
In order to create default values that get overridden by user settings, the data file can use the !set command, which sets an environment variable only if it is not already set; these settings are only for the current units invocation and do not persist. So if the example above were preceded by !set INCH_UNIT france, then this would make france the default value for INCH_UNIT. If the user had set the variable in the environment before invoking units, then units would use the user's value. ๐
To link these settings to the user's locale you combine the !set command with the !locale command. If you wanted to combine the above example with suitable locales you could do it by preceding the above definition with the following:
!locale en_US
!set INCH_UNIT usa
!endlocale
!locale en_GB
!set INCH_UNIT uk
!endlocale
!locale en_CA
!set INCH_UNIT canada
!endlocale
!locale fr_FR
!set INCH_UNIT france
!endlocale
!set INCH_UNIT france
These definitions set the overall default for INCH_UNIT to france and set default values for four locales appropriately. The overall default setting comes last so that it only applies when INCH_UNIT was not set by one of the other commands or by the user. โจ
๐จ If the variable given after!varor!varnotis undefined, thenunitsprints an error message and ignores the definitions that follow. Use!setto create defaults to prevent this situation from arising. The-coption only checks the definitions that are active for the current environment and locale, so when adding new definitions take care to check that all cases give rise to a well defined set of definitions. ๐
๐ ENVIRONMENT VARIABLES ๐
The units program uses the following environment variables:
HOMEโ Specifies the location of your home directory; it's used byunitsto find a personal units data file.units. On systems running Microsoft Windows, the file isunitdef.units, and ifHOMEdoes not exist,unitstries to determine your home directory from theHOMEDRIVEandHOMEPATHenvironment variables; if these variables do not exist,unitsfinally triesUSERPROFILEโ typicallyC:\Users\username(Windows Vista and Windows 7) orC:\Documents and Settings\username(Windows XP). ๐LC_CTYPE,LANGโ Checked to determine the locale ifunitscannot obtain it from the operating system. Sections of the default main units data file are specific to certain locales. ๐ฃ๏ธMYUNITSFILEโ Specifies your personal units data file. If this variable exists,unitsuses its value rather than searching your home directory for.units. The personal units file will not be loaded if any data files are given using the-foption. ๐พPAGERโ Specifies the pager to use for help and for displaying the conformable units. The help function browses the units database and calls the pager using the+nn syntax for specifying a line number. The default pager ismore;PAGERcan be used to specify alternatives such asless,pg,emacs, orvi. ๐UNITS_ENGLISHโ Set to eitherUSorGBto choose United States or British volume definitions, overriding the default from your locale. ๐บ๐ธ๐ฌ๐งUNITSFILEโ Specifies the units data file to use (instead of the default). You can only specify a single units data file using this environment variable. If units data files are given using the-foption, the file specified byUNITSFILEwill not be loaded unless the-foption is given with the empty string (units -f ""). โ ๏ธUNITSLOCALEMAPโ Windows only; this variable has no effect on Unix-like systems. Specifies the units locale map file to use (instead of the default). This variable seldom needs to be set, but you can use it to ensure that the locale map file will be found if you specify a location for the units data file using either the-foption or theUNITSFILEenvironment variable, and that location does not also contain the locale map file. ๐ชUNITS_SYSTEMโ This environment variable is used in the default main data file to select CGS measurement systems. Currently supported systems areesu,emu,gauss[ian],hlu,natural,natural-gauss,planck,planck-red,hartreeandsi. The default issi. โ๏ธ
and bestie we are SO not done yet, keep scrolling ๐
โจ DATA FILES โจ
okay bestie, so units rolls up with six default data files and you're gonna want to know all of them ๐
- the main data file,
definitions.units - the atomic masses of the elements,
elements.units - currency exchange rates,
currency.units - cryptocurrency prices,
crypto.units - precious metals prices,
metal_prices.units - and the US Consumer Price Index,
cpi.units
the last five files get loaded via !include directives inside the main file (peep Database Command Syntax for the deets ๐).
there's also an optional personal units data file called .units (unitdef.units if you're on Windows ๐ช) that lives in your home directory. it gets its own whole moment in Units Data Files.
on Unix-like systems, the data files are typically chilling in /usr/share/units if units came with your OS, or in /usr/local/share/units if you compiled units from the source distribution. and listen โ currency.units, crypto.units, metal_prices.units, and cpi.units are symbolic links to another location. sneaky little links, iconic behavior ๐
on Microsoft Windows systems, the files may sit in those same spots if Unix-like commands are available, a Unix-like file structure is present (like C:/usr/local), and units is compiled from the source distribution. if Unix-like commands aren't available, the more common location is C:\Program Files (x86)\GNU\units (for 64-bit Windows installations) or C:\Program Files\GNU\units (for 32-bit installations).
and if units came from the GNU Win32 Project (http://gnuwin32.sourceforge.net/), the files commonly live in C:\Program Files\GnuWin32\share\units.
lowkey important: if the default main units data file is not an absolute pathname, units will go looking for the file in the directory that contains the units program. if it's not there, units checks a directory ../share/units relative to the directory with the units program. ๐ต๏ธ
you can figure out where the files are by running units --version. and running units --info gives you extra tea about the files, how units will try to find them, and the status of the related environment variables. go off โจ
๐ฆ UNICODE SUPPORT ๐ฆ
the standard units data file is in Unicode, using UTF-8 encoding. most definitions stick to plain ASCII (that's code points U+0000 through U+007F), and the definitions that do use non-ASCII characters show up in blocks that start with !utf8 and end with !endutf8. ๐
those non-ASCII definitions load only if the platform and the locale support UTF-8. platform support is decided when units is compiled; the locale gets checked at every single invocation of units. wanna see if your version of units has Unicode support? just run the program with the --version option. easy peasy ๐
when Unicode support is available, units checks every line within UTF-8 blocks in all of the units data files for invalid or non-printing UTF-8 sequences. if it finds any, units ignores the entire line. besides checking validity, units also figures out the display width of non-ASCII characters so the pointer lands in the right spot in some error messages, and so columns line up for the search and ? commands. alignment queen ๐
Microsoft Windows supports UTF-8 in console applications running in Windows Terminal โ but UTF-8 is not supported in applications running in the older Windows Console Host (see Unicode Support on Windows). and nope, the UTF-16 and UTF-32 encodings are not supported on any platforms. ๐
if Unicode support is available and you add definitions containing non-ASCII UTF-8 characters to a units data file, those definitions should be wrapped in !utf8 ... !endutf8 so they only load when Unicode support is there. as usual, the ! must appear as the first character on the line. and like it says in Units Data Files, it's usually best to put definitions like that in supplemental data files linked by an !include command, or in a personal units data file. ๐ซถ
when Unicode support is not available, units makes zero assumptions about character encoding โ except that characters in the range 00โ7F hexadecimal correspond to ASCII encoding. non-ASCII characters are just sequences of bytes with no special meanings. for definitions in supplementary units data files, you can use any encoding consistent with that assumption. for example, if you wanna use non-ASCII characters in definitions while running units under Windows, you can use a character set like Windows "ANSI" (code page 1252 in the US and Western Europe) โ and if you do that, the console code page must be set to the same encoding or the characters won't display right. you can even use UTF-8, though some messages may be improperly aligned, and units will not detect invalid UTF-8 sequences. and if you use UTF-8 encoding when Unicode support isn't available, you should put any definitions with non-ASCII characters outside !utf8 ... !endutf8 blocks โ otherwise they'll just get ignored. rude but true ๐ญ
except for code examples, typeset material usually uses the Unicode symbols for mathematical operators. to make copying and pasting from those sources easier, several typographical characters get converted to the ASCII operators used in units:
- the figure dash (U+2012), minus (
-; U+2212), and en dash (โ; U+2013) are converted to the operator- - the multiplication sign (
ร; U+00D7), N-ary times operator (U+2A09), dot operator (โ; U+22C5), and middle dot (ยท; U+00B7) are converted to the operator* - the division sign (
รท; U+00F7) is converted to the operator/ - and the fraction slash (U+2044) is converted to the operator
|
๐ Unicode Support on Windows ๐
Microsoft Windows supports UTF-8 in console applications running in Windows Terminal, but not in applications running in the older Windows Console Host. in Windows Terminal, the code page must be set to 65001 for UTF-8 to be enabled. with the UTF-8 code page, running units -V might show you this:
GNU Units version 2.24
Without readline, with UTF-8, locale English_United States (en_US)
two values are shown for the locale: the first is the one returned by the system; the second is the POSIX value that the system value gets mapped to. โจ
with a different code page, the result might be:
GNU Units version 2.24
Without readline, with UTF-8 (disabled), locale English_United States (en_US)
To enable UTF-8: set code page to 65001
and if units is running in Windows Console Host, no matter what the code page is, the result might be:
GNU Units version 2.24
Without readline, with UTF-8 (disabled), locale English_United States (en_US)
To enable UTF-8: run in Windows Terminal and set code page to 65001
the UTF-8 code page can be set by running chcp 65001. ๐
heads up: as of late 2024, the Windows build of units does not identify characters โ typically East Asian ones โ that occupy more than one column, and error messages involving those characters may not be properly aligned. so your vibes might be off by a column or two ๐
๐ READLINE SUPPORT ๐
if the readline package has been compiled in, then when units is used interactively, you get numerous command line editing features. to check if your version of units includes readline, run the program with the --version option. ๐
for complete information about readline, go consult the documentation for the readline package. without any configuration, units lets you edit in the style of emacs. and particularly useful with units? the completion commands. ๐ฆ
type a few characters and then hit ESC followed by ?, and units will show you a list of all the units that start with the characters you typed. for example, if you type metr and then request completion, you'll see something like this:
You have: metr
metre metriccup metrichorsepower metrictenth
metretes metricfifth metricounce metricton
metriccarat metricgrain metricquart metricyarncount
You have: metr
if there's a unique way to complete a unit name, you can hit the TAB key and units will fill in the rest of the unit name for you. if units beeps? that means there's no unique completion. press TAB a second time and it'll print the list of all completions. bestie really said "here are your options" ๐
the readline library also keeps a history of the values you enter. you can move through that history using the up and down arrows. the history gets saved to the file .units_history in your home directory so it persists across multiple units invocations. if you wanna keep work for a certain project separate, you can change the history filename using the --history option. you could, for example, make an alias for units to units --history .units_history so that units would save separate history in the current directory. the length of each history file is limited to 5000 lines. and note also that if you run several concurrent copies of units, each one will save its new history to the history file upon exit. ๐
๐ธ UPDATING CURRENCY EXCHANGE RATES AND CPI ๐ธ
Currency Exchange Rates
okay bestie so here's the tea: the units program database ships with currency exchange rates and prices for some precious metals. and likeโฆ those values change over time. sometimes very rapidly. and units literally cannot give you real-time values, no cap. so to update the exchange rates you run units_cur, which rewrites the file containing the currency rates โ typically /var/lib/units/currency.units or /usr/local/com/units/currency.units on a Unix-like system, or C:\Program Files (x86)\GNU\units\definitions.units on a Windows system. ๐ซถ
This program requires Python 3 (https://www.python.org). and it must be run with suitable permissions to write that file, so like, mind your perms bestie. To keep the rates updated automatically, run it using a cron job on a Unix-like system, or a similar scheduling program on a different system. โจ
Reliable free sources of currency exchange rates have been annoyingly ephemeral โ it's giving unreliable narrator tbh. The program currently supports several sources:
- ExchangeRate-API.com (https://www.exchangerate-api.com). The default currency server. Allows open access without an API key, with unlimited API requests. Rates update once a day, the US dollar (
USD) is the default base currency, and you can choose your base currency with the-boption described below. You can optionally sign up for an API key to access paid benefits such as faster data update rates. - FloatRates (https://www/floatrates.com). The US dollar (
USD) is the default base currency. You can change the base currency with the-boption described below. Allowable base currencies are listed on the FloatRates website. Exchange rates update daily. - The European Central Bank (https://www.ecb.europa.eu). The base currency is always the euro (
EUR). Exchange rates update daily. This source offers a more limited list of currencies than the others. - Fixer (https://fixer.io). Registration for a free API key is required. With a free API key, base currency is the euro; exchange rates are updated hourly, the service has a limit of 1,000 API calls per month, and SSL encryption (
httpsprotocol) is not available. Most of these restrictions are eliminated or reduced with paid plans. - open exchange rates (https://openexchangerates.org). Registration for a free API key is required. With a free API key, the base currency is the US dollar; exchange rates are updated hourly, and there is a limit of 1,000 API calls per month. Most of these restrictions are eliminated or reduced with paid plans.
The default source is FloatRates; you can select a different one using the -s option described below. ๐
Crypto and Precious Metals Prices
Cryptocurrency prices are obtained from coingecko (coingecko.com). Precious metals pricing is obtained from Packetizer (www.packetizer.com); this site updates once per day. ๐ช
US Consumer Price Index
The units program includes the US Consumer Price Index (CPI) published by the US Bureau of Labor Statistics: specifically, the Consumer Price Index for All Urban Consumers (CPI-U), not seasonally adjustedโSeries CUUR0000SA0. ๐
The units_cur command updates the CPI and saves the result in cpi.units in the same location as currency.units. The data are obtained via the BLS Public Data API (https://www.bls.gov/developers/). These data update once a month. When units_cur runs it will only attempt to update the CPI data if the current CPI data file is from a previous month, or if the current date is after the 18th of the month.
Invoking units_cur
You invoke units_cur like this:
units_cur [options] [currency_file] [crypto_file] [metals_file] [cpi_file]
By default, the output is written to the default currency, crypto, metals, and CPI files described above; this is usually what you want, because this is where units looks for the files. If you wish, you can specify different filenames on the command line and units_cur will write the data to those files. If you give - for a file it will write to standard output. The special filename . skips the update for that file. (iconic behaviour honestly)
The following options are available:
-h,--helpโ Print a summary of the options forunits_cur.-V,--versionโ Print theunits_curversion number.-v,--verboseโ Give slightly more verbose output when attempting to update currency exchange rates.-c coingecko,packetizer,--crypto coingecko,packetizerโ Set crypto data source (default:coingecko).-s source,--source sourceโ Specify the source for currency exchange rates; currently supported values arefloatrates(for FloatRates),eubank(for the European Central Bank),fixer(for Fixer), andopenexchangerates(for open exchange rates); the last two require an API key to be given with the-koption.-b base,--base baseโ Set the base currency (when allowed by the site providing the data). base should be a 3-letter ISO currency code, e.g.,USD. The specified currency will be the primitive currency unit used byunits. You may find it convenient to specify your local currency. Conversions may be more accurate and you will be able to convert to your currency by simply hitting Enter at theYou want:prompt. This option is ignored if the source does not allow specifying the base currency. (Currently onlyfloatratessupports this option.)-k key,--key keyโ Set the API key to key for currency sources that require it.--blskey BLSkeyโ Set the US Bureau of Labor Statistics (BLS) key for fetching CPI data. Without a BLS key you should be able to fetch the CPI data exactly one time per day. If you want to use a key you must request a personal key from BLS.
๐ DATABASE COMMAND SYNTAX ๐
okay so this is the whole syntax menu for the definitions file, bestie. every single one, no skips ๐
unit definitionDefine a regular unit.prefix- definitionDefine a prefix.- ``` funcname(var) noerror units=[in-units,out-units] domain=[x1,x2] range=[y1,y2] definition(var) ; inverse(funcname)
Define a nonlinear unit or unit function. The four optional keywords `noerror`, `units=`, `range=` and `domain=` can appear in any order. The definition of the inverse is optional.
- `tabname[out-units] noerror pair-list`
Define a piecewise linear unit. The pair list gives the points on the table listed in ascending order. The `noerror` keyword is optional.
- `!endlocale`
End a block of definitions beginning with `!locale`
- `!endutf8`
End a block of definitions begun with `!utf8`
- `!endvar`
End a block of definitions begun with `!var` or `!varnot`
- `!include file`
Include the specified file.
- `!locale value`
Load the following definitions only of the locale is set to *value*.
- `!message text`
Display *text* when the database is read unless the quiet option (`-q`) is enabled. If you omit *text*, then `units` will display a blank line. Messages will also appear in the log file.
- `!prompt text`
Prefix the `You have:` prompt with the specified *text*. If you omit *text*, then any existing prefix is canceled.
- `!set variable value`
Sets the environment variable, *variable*, to the specified *value* only if it is not already set.
- `!unitlist alias definition`
Define a unit list alias.
- `!utf8`
Load the following definitions only if `units` is running with UTF-8 enabled.
- `!var envar value-list`
Load the block of definitions that follows only if the environment variable *envar* is set to one of the values listed in the space-separated *value* list. If *envar* is not set, `units` prints an error message and ignores the block of definitions.
- `!varnot envar value-list`
Load the block of definitions that follows only if the environment variable *envar* is set to *value* that is not listed in the space-separated *value* list. If *envar* is not set, `units` prints an error message and ignores the block of definitions.
---
# ๐ FILES ๐
- `/usr/share/units/definitions.units` โ the standard units data file ๐ธ
---
# ๐ AUTHOR ๐
`units` was written by Adrian Mariano
---
that's a wrap on the whole page bestie, we literally made it to the end ๐ this version is the `UNITS(1)` page, dated **29 March 2026** โ go forth and convert things with main character energy โจ๐
๐ฆ
๐ฆ where this page comes from
- fedora 44: units 2.27-1.fc44 ยท GPL-3.0-or-later
- ubuntu stonking: units 2.27-1 ยท GPL-3.0-or-later
- Copyright 1996, 1997, 1999, 2000, 2001, 2002, 2004, 2005, 2007 2011-2024, 2026 Free Software Foundation, Inc
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms