# 02 — What a code answers: dimension, factor, kind, conversion, symbol, name, canonical form, a float's range {#values}

Each function of a code answers `{:ok, value}`, or `parse/1`'s `{:error, reason}` for a
string that is not a code; a term that is no string is `{:syntax, text}`. Each has a `!`
twin that answers the value alone or raises `Ucum.Error` (spec/00 §3, spec/03).

## 1. Dimension {#values-dimension}

`Ucum.dimension/1` answers a code's dimension: a map from each base dimension to its
exponent, `%{}` when the code is dimensionless. It is the sum of its components'
dimensions, each times its exponent, a quotient's negated. A factor and an annotation add
none. The dimensions are UCUM's seven, one per base unit: `:length` (`m`), `:time` (`s`),
`:mass` (`g`), `:angle` (`rad`), `:temperature` (`K`), `:charge` (`C`) and
`:luminous_intensity` (`cd`). The mole is UCUM's number, so `mol` is dimensionless and
`mmol/l` has the dimension of `/l`; the bit is `1`, so `By` is dimensionless and `By/s` has
the dimension of `Hz`. A special unit has the dimension of its function's argument: `B`
none, `B[SPL]` that of `Pa`.

An arbitrary unit (spec/01 §3) is a dimension of its own, an eighth kind of key: its
code, a string. `[arb'U]` is `%{"[arb'U]" => 1}` and `[IU]/mL` is
`%{"[iU]" => 1, length: -3}`, the international unit's two codes being one unit.

## 2. Factor {#values-factor}

`Ucum.factor/1` answers a code's exact factor to its base: the product of each
component's factor (its prefix's times its atom's, or the integer) raised to its exponent.
It is a rational `{n, d}`, reduced, or `{n, d, k}`, n/d·πᵏ with k ≠ 0, for a code holding
`deg`; π cancels between two angles (`deg/deg` is `{1, 1}`). A code holding a special
unit (`Cel`, `[degF]`, `B`, `B[SPL]`, `[pH]`, …, spec/01 §3) has no ratio to its base, so no factor:
`{:ok, nil}`. So `bit` is `{1, 1}`, `By` `{8, 1}` and `MiBy` `{8388608, 1}`.

A factor is held up to a stated size (spec/01 §6): a code whose factor is past it,
`km999999`, is `{:error, {:too_large, code}}` here and from every function that takes a
factor.

```test:units-dimension-factor
a code's dimension sums its components' and its factor is exact, π kept as a power; the dimensions are UCUM's seven; a level has its argument's dimension and no factor; kind/1 tells linear, affine and nonlinear codes apart; a string that is not a code is parse/1's fault, never a raise, and the ! twins raise it
```

## 3. Kind {#values-kind}

`Ucum.kind/1` answers how a code's values relate to its base: `:affine` when it holds
`Cel`, `[degF]` or `[degRe]` (a scale with an offset), `:nonlinear` when it holds any
other special unit (`B`, `B[SPL]`, `Np`, `[pH]`, `[p'diop]`, …; spec/01 §3), whose
function is a logarithm, a tangent or a root, else `:linear`. A code holding both an
affine and a nonlinear unit is `:affine`.

## 4. Conversion {#values-conversion}

`Ucum.conversion(from, to)` answers `{:ok, {scale, offset}}`, so that a value in `from` is
`value × scale + offset` in `to`: `scale` an exact factor (`{n, d}`, or `{n, d, k}` for
n/d·πᵏ) and `offset` an exact signed rational `{n, d}`. Or `{:error, reason}`:

- **The same code** converts by `{{1, 1}, {0, 1}}`.
- **Two codes of one dimension with factors** convert by the ratio of their factors,
  offset `{0, 1}`: `[lb_av]` to `kg` is `{45359237, 100000000}`, `deg` to `rad` is
  `{1, 180, 1}`, `[mi_i]/h` to `km/h` is `{25146, 15625}`.
- **The affine units** convert with their offsets, standing alone. UCUM defines `Cel` as
  `K` less 273.15, `[degF]` as 5/9 `K` from 459.67 below its zero and `[degRe]` as 5/4 `K`
  from the ice point, so `[degRe]` to `Cel` is `{{5, 4}, {0, 1}}`, `Cel` to
  `[degF]` is exactly `{{9, 5}, {32, 1}}` and `[degF]` to `K` is `{{5, 9}, {45967, 180}}`;
  a prefixed one scales with its prefix (`mK` to `Cel`).
- **Any other special unit converts to itself under another prefix**, by the ratio of the
  prefixes: `B` to `dB` is `{10, 1}`, `dB[SPL]` to `B[SPL]` is `{1, 10}`. To any other
  code of its dimension it converts through its function (§6), which is no scale and
  offset: `{:not_linear, from, to}`. So `dB` to `1`, `%` to `dB`, `dB[SPL]` to `Pa` and
  `Np` to `B` are refused with it by `conversion/2`, and `convert/3` converts a value
  between them.
- **A special unit converts standing alone**, with a prefix or without (UCUM §22). Inside
  a term (`Cel/h`, `Cel2`, `dB/s`, `2.dB`) it is no unit of a scale: a temperature per
  hour has no offset, and a level per second no logarithm. Either code holding one so is
  `{:special_in_term, code}`.
- **Two codes of different dimensions** are `{:dimension, from, to}`, whatever they hold:
  `s` to `By`, and `dB` to `dB[SPL]` (a ratio's level and a pressure's).
- **An arbitrary unit converts to itself and to nothing else**, by the rules above, being
  a dimension of its own: `[IU]/mL` to `k[IU]/L` is `{{1, 1}, {0, 1}}`, and `[IU]` to `1`,
  to `mg` and to `[arb'U]` are each `{:dimension, from, to}`. UCUM (§24–25) says an
  arbitrary unit, and any term holding one, is comparable with no *other* unit or term;
  the library reads a term as comparable with a term of the same arbitrary unit to the
  same power, since a prefix or a volume beside it changes nothing of its meaning.

Data converts as UCUM defines it: `By` to `bit` is `{8, 1}`, `By/s` to `Hz` is `{8, 1}`, and
1 `By` is 800.0 `%`.

`Ucum.convert(value, from, to)` is `value × scale + offset` as a float. The value is
taken as the exact number it is (a float is a ratio of two integers), the scale and
offset are exact, and the arithmetic is in integers, rounded once where the float is
made; a power of π is held exactly enough to be rounded with them, once (§9). A pair that is
`{:not_linear, from, to}` to `conversion/2` it converts through the special units'
functions (§6). Any other pair `conversion/2` refuses is its `{:error, reason}`, a
value that is no number is `{:error, :not_a_number}`, and an answer past what a float
holds is `{:error, {:out_of_range, value, from, to}}` (§9). So 100 `Cel` is 212.0 `[degF]`,
−40 `Cel` is −40.0 `[degF]`, 0 `K` is −273.15 `Cel`, 180 `deg` is π `rad`, 30 `dB` is 3.0
`B` and 30 `dB` is 1000.0 `1`.

`Ucum.convert(value, conversion)` applies `{scale, offset}` from `conversion/2` to a value
without reading the unit codes again: the same exact arithmetic and single rounding as
`convert/3`, bit for bit, for every pair `conversion/2` answers (`convert/3` applies
`convert/2` after `conversion/2` for those pairs). It answers `{:ok, float}`,
`{:error, :not_a_number}` for a value that is no number, `{:error, {:not_a_conversion,
term}}` for a conversion of another shape (spec/03 §2), and `{:error, :out_of_range}` for
an answer past what a float holds (§9; no codes to name). A hand-made `{scale, offset}`
of any size is answered without raising; one whose integers are past `conversion/2`'s
bound (twice spec/01 §6's) is worked in wide arithmetic, like a huge integer value (§9).
Pairs that go through a special unit's function (§6) stay with `convert/3`.

```test:units-convert
codes of one dimension convert by their factors exactly; the affine units by their offsets, alone; a level exactly to itself under another prefix, and otherwise not linearly; a special unit inside a term is refused; data converts as dimensionless; other dimensions are refused with the reason; a value converts there and back to itself, and conversions compose exactly
```

```test:units-convert-resolved
convert/2 after conversion/2 equals convert/3 bit for bit for every pair conversion/2 answers; a non-number or an answer past a float is refused with the reason, and a hand-made conversion of any size never raises
```

## 5. The display symbol {#values-symbol}

`Ucum.symbol/2` writes a code as a reader reads it:

- each atom by the table's symbol, UCUM's print symbol for it (spec/01 §3), and each
  prefix by its own, `u` as `μ`;
- a positive exponent above one as superscript digits (`m2` → `m²`);
- the components with a positive exponent joined by `·`, then `/` and those with a
  negative one by their magnitude, in parentheses when there are two or more: `kW.h` →
  `kW·h`, `By/s` → `B/s`, `g/m/s2` → `g/(m·s²)`, `s-1` → `/s`, `[ft_i]2` → `ft²`,
  `mm[Hg]` → `mm Hg`, `dB[SPL]` → `dB(SPL)`, `deg` → `°`;
- the factor `1` and annotations are dropped, so `1` and `{request}` are `""` and
  `{request}/s` is `/s`; any other factor is written (`10.m` → `10·m`).

With `annotations: true`, an annotation that stands alone as a component is written as its
text without braces (`{request}/s` → `request/s`). One attached to a unit is dropped even
then, the unit saying more than its note (`By{heap}` → `B`). `:annotations` is the one
option: any other, an `:annotations` that is no boolean, or options that are no keyword
list are refused with `{:bad_options, opts}` (spec/03 §4), a misspelt option being a
wrong symbol otherwise.

```test:units-symbol-written
each code is written as a reader reads it, by the table's symbols, superscripts and · and /; annotations: true writes a lone annotation's text and never one on a unit; every code has a symbol
```

## 6. The special units' functions {#values-special}

UCUM defines a special unit (its specification's §21–23) by a **proper unit** `u` and a
pair of functions, `f` and its inverse: a value `r` in the special unit is `f(m/u)` for
the quantity `m`, and `m` is `f⁻¹(r) × u`. A prefix scales the value, not the unit
(§22): with the prefix's factor α, `r = f(m/u) / α` and `m = f⁻¹(α·r) × u`, so a decibel
is a tenth of a bel.

The table's definition names both (spec/01 §3): `2lg(2 10*-5.Pa)` is the function `2lg`
over the proper unit 2 × 10⁻⁵ `Pa`. The functions are the specification's:

| Function | `f(x)` | `f⁻¹(r)` | Units |
|---|---|---|---|
| `cel` | x − 273.15 | r + 273.15 | `Cel` |
| `degf` | x − 459.67 | r + 459.67 | `[degF]`, over 5/9 `K` |
| `degre` | x − 218.52 | r + 218.52 | `[degRe]`, over 5/4 `K` |
| `lg` | lg x | 10ʳ | `B`, `B[W]`, `B[kW]` |
| `2lg` | 2 lg x | 10^(r/2) | `B[SPL]`, `B[V]`, `B[mV]`, `B[uV]`, `B[10.nV]` |
| `ln` | ln x | eʳ | `Np` |
| `ld` | log₂ x | 2ʳ | `bit_s` |
| `pH` | −lg x | 10⁻ʳ | `[pH]`, over `mol/l` |
| `hpX`, `hpC`, `hpM`, `hpQ` | −log x to the base 10, 100, 1,000, 50,000 | that base to −r | `[hp'_X]`, `[hp'_C]`, `[hp'_M]`, `[hp'_Q]` |
| `100tan` | 100 tan x | arctan(r/100) | `[p'diop]`, `%[slope]`, over `rad` |
| `sqrt` | √x | r² | `[m/s2/Hz^(1/2)]`, over `m2/s4/Hz` |

The first three are the affine units of §4, which convert exactly and are in this table
only to complete it. The others are floats: `convert/3` takes the value to the base
units by the one code's function and from them by the other's, a code with a factor
being its own proper unit. So 94 `dB[SPL]` is 2 × 10⁻⁵ × 10^4.7 `Pa`, 7 `[pH]` is 10⁻⁷
`mol/l`, 100 `[p'diop]` is 45 `deg`, and 1 `Np` is lg e `B`.

The file writes `%[slope]`'s definition twice and differently: `100tan(1 rad)` as the
special expression, `deg` in its `<function>` element. The expression is the
specification's form (its §23) and its table's, and is what is read (spec/01 §3): a
slope of 100 % is 45°.

**A value a function has no answer for** is `{:error, {:out_of_domain, value, from, to}}`:
a logarithm of a number that is not positive (0 `1` in `dB`) and a root of a negative
one. Every value has a power: 5,000 `B` as a number is 10⁵⁰⁰⁰, an answer a float does
not hold, which is §9's `{:out_of_range, value, from, to}` and no fault of the function;
5,000 `B` is 50,000.0 `dB`, and 10⁴⁰⁰ as a number is 400.0 `B`. A power too small for a
float is 0.0, as a float has it.

```test:units-special
each special unit's function converts the values UCUM's definition gives; every special unit that is not affine converts to its proper unit and back to itself; a value a function has no answer for is refused with the reason, never raised
```

## 7. The name {#values-name}

`Ucum.name/1` writes a code's name: the code **as it is written**, each unit by the name
UCUM's table gives it (spec/01 §3; the first, where it gives several), in the form the
UCUM functional tests fix (spec/04). It answers `{:ok, name}`, or `parse/1`'s
`{:error, reason}`.

- A unit is its prefix's name and its own, run together, in parentheses: `m` is
  `(meter)`, `mm` `(millimeter)`, `m[H2O]` `(meter of water column)`.
- An exponent is written as the code has it, after ` ^ `, inside the parentheses: `rad2`
  is `(radian ^ 2)`, `s-2` `(second ^ -2)`. An exponent of 1 is not written.
- `.` is ` * ` and `/` is ` / `, in the code's order. The name does not work the code
  out: `m3.kg-1.s-2` is `(meter ^ 3) * (kilogram ^ -1) * (second ^ -2)`, and `m3/kg/s2`
  is `(meter ^ 3) / (kilogram) / (second ^ 2)`.
- A factor is its digits: `4.[pi].10*-7.N/A2` is
  `4 * (the number pi) * (the number ten for arbitrary powers ^ -7) * (newton) / (ampère ^ 2)`.
- A term in parentheses keeps them, around its name: `g/(m.s2)` is
  `(gram) / ((meter) * (second ^ 2))`. Around one component they add nothing: `((m))` is
  `(meter)`.
- A leading `/` is `/ ` before the term it divides by, which is in parentheses when it
  is more than one component: `/s` is `/ (second)`, `/s.m` is `/ ((second) * (meter))`.
- An annotation standing alone is `(unity)`, which it means (spec/01 §2): `{rbc}/uL` is
  `(unity) / (microliter)`. One on a unit or a factor is not written: `kg{wet}` is
  `(kilogram)`, `1{c}` is `1`.

The functional tests fix the form of a unit, an exponent, a factor and the two operators.
For a term in parentheses, a leading `/` and an annotation they have no case, and the
form here is the library's.

```test:units-name
each code is named as it is written, by the table's names, in the functional tests' form; a term in parentheses, a leading / and an annotation are written as specified; every code has a name; a string that is not a code is parse/1's fault
```

## 8. The canonical form and quantity arithmetic {#values-canonical}

`Ucum.canonical/1` answers a code in UCUM's base units: `{:ok, {factor, code}}`, where
`factor` is `factor/1`'s (§2; `nil` for a code holding a special unit) and `code` is the
**canonical code** of its dimension (§1):

- the base units it holds, in UCUM's order `m`, `s`, `g`, `rad`, `K`, `C`, `cd`, then any
  arbitrary units in the order of their codes;
- each with its exponent, 1 not written, joined by `.`;
- `1` for a dimensionless code.

So `km/h` is `{{5, 18}, "m.s-1"}`, `N` is `{{1000, 1}, "m.s-2.g"}`, `%` is `{{1, 100}, "1"}`,
`[IU]/mL` is `{{1000000, 1}, "m-3.[iU]"}` and `Cel` is `{nil, "K"}`. One of a code is its
factor of its canonical code: `conversion(code, canonical_code)` is `{factor, {0, 1}}`.
A canonical code is its own: its factor is 1 and its canonical code itself.

A **quantity** is `{value, code}`, a number with its unit. `Ucum.multiply/2` and
`Ucum.divide/2` answer two quantities' product and quotient as `{:ok, {value, code}}`: the
value a float in base units, the code canonical. The product's dimension is the sum of
the two, the quotient's their difference; the value is the two values' product or
quotient times the two factors', worked exactly and rounded once as `convert/3`'s is
(§4). So 1.5 `g` times 2 `m` is 3.0 `m.g`, 2 `kW` times 3 `h`
is 2.16 × 10¹⁰ `m2.s-2.g`, and 90 `km` over 2 `h` is 12.5 `m.s-1`. Two quantities of one
dimension divide to the unity: 1 `[mi_i]` over 1 `km` is 1.609344 `1`.

The answer is in base units, not in the codes given: `g.m` and `m.g` are one unit, and
UCUM defines no order of one over the other. A program that wants the answer in a code
of its own converts it (`convert/3`).

They refuse (spec/03 §3):

- a quantity whose code holds a special unit, with `{:special_in_term, code}`: a special
  unit takes part in no product (UCUM §22), 2 `Cel` times 3 `m` being no quantity;
- an argument that is no `{value, code}` pair, with `{:not_a_quantity, term}`;
- a value that is no number, with `:not_a_number`;
- a divisor of value zero, with `:division_by_zero`;
- a product or a quotient past what a float holds, with `:out_of_range` (§9);
- a code that does not read, with `parse/1`'s reason.

An arbitrary unit multiplies and divides as the dimension it is: 5 `[IU]` over 2 `mL` is
2,500,000.0 `m-3.[iU]`.

```test:units-canonical
a code's canonical form is its factor and the code of its dimension, the base units in UCUM's order; a canonical code is its own; a code converts to its canonical code by its factor; two quantities multiply and divide into base units, a product and a quotient undoing each other; a special unit, a value that is no number and a divisor of zero are refused
```

## 9. A float's range {#values-range}

`convert/2`, `convert/3`, `multiply/2` and `divide/2` answer a float, and a float has a
range: its magnitude is at most 1.7976931348623157 × 10³⁰⁸. The value given may be any
number: a float anywhere in that range, or an integer of any size, which has none.

**An answer past the range is refused with a reason, and nothing raises** (spec/00 §3):
`{:error, {:out_of_range, value, from, to}}` from `convert/3`, `{:error, :out_of_range}`
from `convert/2`, `multiply/2` and `divide/2`. So 10³⁰⁰ `Gm` in `nm` is refused, being
10³¹⁸, and so is the integer 10⁴⁰⁰ in `m` as `m`, which is no float.

**An answer inside the range is given, whatever the size of what it is made of.** The
range is the answer's, not the arithmetic's: the value, a factor or a step on the way may
be past a float while the answer is not. The integer 10⁴⁰⁰ `m` is 10.0 `10*399.m`, 3
`10*400` is 30.0 `10*399`, 10⁴⁰⁰ `m` over 10⁴⁰⁰ `s` is 1.0 `m.s-1`, and 5,000 `B` is
50,000.0 `dB`. The largest float converts to itself.

**An answer below the range is zero**, as a float has it: 10⁻³⁰⁰ `ym` is 0.0 `Ym`. A
float's smallest values, the subnormals, are answers: 10⁻³⁰⁰ `nm` is 10⁻³¹⁸ `Gm`. One is
rounded to a float's precision and then to the subnormal's fewer bits, so it may be
rounded twice, and is within one of the least subnormal of the nearest.

A special unit's value past a float (a prefix can make it one) is, to its function, the
same as the largest float: 10 to it is past any range, 10 to minus it is zero, and its
arc tangent is a right angle. Its square is the square. An angle past a float has no
tangent a float holds, and is `:out_of_range`.

A code's factor may itself be past a float: `[pi]700` and `Ym20` are codes with factors
(§2), exact as ratios, and convert wherever the answer is a float.

**A power of π is rounded with the rest, once.** π is held to 576 bits, worked out
while the library compiles, and πᵏ to 256 bits, so for every power a code or
`conversion/2` carries (|k| ≤ 65,536, spec/01 §6) and any up to 2⁶⁴, value × n/d·πᵏ is
the float nearest it, unless it lies within 2⁻¹⁵⁰ of halfway between two floats.
`[pi]1000` in `10*497` is the float nearest π¹⁰⁰⁰/10⁴⁹⁷, as `[pi]` in `1` is `:math.pi()`.
Past 2⁶⁴, which only a hand-made `convert/2` scale reaches, πᵏ is 2^(k·log₂π), log₂π
held to 256 bits: of its magnitude and increasing with k. No number the machine holds
brings such a power back within a float, so the answer is `:out_of_range` or zero. A
π scale with an offset, which `conversion/2` never answers, is rounded and then the
offset added: a second rounding.

**An integer value may be of any size the machine holds.** One of more bits than the
exact arithmetic can use (twice the bound of a factor and a float's range more, spec/01
§6) is rounded to a float's precision first and carried with its exponent, so the answer
may be rounded twice. By any scale such a value is past a float, and is `:out_of_range`;
two of them divide to their quotient.

```test:units-range
a number without a range is the float where a float holds it, and rounds once; an answer past a float's range is refused with the reason by convert/2, convert/3, multiply/2 and divide/2, and one inside it is given whatever its parts; one below it is zero; a special unit's function answers a value past a float; every unit of the table converts, multiplies and divides any number with an answer, never a raise
```
