Shared types, constants and utilities
| Problem | Give every crate a common error type, numeric traits, aliases and physical and mathematical constants, and provide small helpers: floating-point spacing, unit conversion and plots drawn in a terminal |
| Devised by | CODATA Task Group on Fundamental Constants (2022 adjustment); IEEE 754 (1985), floating-point arithmetic; the Unicode Braille Patterns block (1999), terminal plots |
| Accuracy | 88 constants checked: mathematical ones to within of mpmath; physical ones within CODATA’s uncertainties; unit factors exact or to double precision (tables below) |
| Cost | Constants are compile-time values; conversions and spacing helpers ; a plot |
| Read first | Preliminaries: floating-point arithmetic |
| API | ErrorsJSL, IsLinearOperatable, IsAnalytic, constants (math, physics, em, dsp, ml, units), codata (physical_constant, value, unit, precision, find), ulp, ulps_between, approx_eq_ulps, machine_epsilon, unit_conversion, render_terminal_plot, render_polar_plot |
Overview
Two crates hold what the rest of the library shares. lib_jsl_core defines the error enum every fallible function returns, the numeric traits that let routines work on real and complex numbers alike, array aliases, and about three hundred named constants: mathematical, physical (CODATA 2022), electromagnetic, signal-processing, machine-learning and unit-conversion values. lib_jsl_utils adds small tools:
- the spacing of floating-point numbers, for setting tolerances and comparing results;
- conversion between units of measure, refusing mixed dimensions;
- line and polar plots drawn with Braille characters, for quick looks at data in a terminal.
Where it is used
Common types and constants keep the crates consistent.
- Error handling. Every function in the library reports failure with the same error type, so you can propagate it with
?through your own programs. - Physical constants. Speed of light, Boltzmann’s constant, the elementary charge and similar values are defined once, with their units, for engineering and physics calculations.
- Numeric traits. Generic code (for real and complex data) is written once.
History
Physical constants are adjusted every four years by CODATA’s Task Group on Fundamental Constants, which fits all relevant measurements together. Since the 2019 redefinition of the SI, the speed of light, Planck’s constant, the elementary charge, Boltzmann’s constant and Avogadro’s number are exact by definition. Others, such as the gravitational constant and the electron mass, are measured, with stated uncertainties. IEEE 754 (1985), led by William Kahan, standardised binary floating point, including the machine epsilon and the “unit in the last place” used to judge accuracy. Unit-conversion tables go back to the 1959 international yard and pound agreement, which fixed the inch at exactly 25.4 mm. Text plots are as old as line printers. Using the 2×4-dot Braille cells added to Unicode in 1999 gives eight sub-pixels per character, the trick behind modern terminal plotting tools.
The idea
Errors and numeric traits
Every fallible function in the workspace returns Result<T, ErrorsJSL>. The variants say what went wrong: input out of range, mismatched array sizes, a runtime failure (such as a negative cycle or a singular matrix), a misconfiguration or a missing feature. Each carries a short message.
pub enum ErrorsJSL {
/// The requested case is not implemented.
NotImplementedYet,
/// Two sizes that must agree do not.
IncompatibleArraySizes((usize, usize)),
/// An argument is outside its valid range or otherwise invalid.
InvalidInputRange(&'static str),
/// A computation failed: no convergence, a singular system, a non-finite value.
RuntimeError(&'static str),
/// An optional dependency or input that the operation needs is missing.
MissingDependency(&'static str),
/// Anything else.
Other(&'static str),
/// An object was configured inconsistently before use.
Misconfiguration(&'static str),
/// A linear-algebra failure, with the message of the underlying `LinalgError`.
LinearAlgebra(String),
/// A failure described by a message built at run time.
Message(String),
}
Generic numerical code is written against two traits. IsLinearOperatable bundles the arithmetic operators. IsAnalytic adds conjugation, exponentials, powers, magnitude and phase. Both are implemented for f64 and Complex<f64>, so one FFT or filter routine serves real and complex data.
Constants
The constants are grouped by field. Physical ones follow CODATA 2022. Exact ones are written exactly, and derived ones (the reduced Planck constant, the gas constant, the Bohr radius) are computed at compile time from their definitions, so the set is self-consistent. The book’s generator checks the mathematical constants against 40-digit mpmath values, and the physical and unit constants against SciPy’s CODATA 2022 tables:
Table 26.1. Physical constants against their reference values.
| module | reference | constants checked | largest relative difference |
|---|---|---|---|
em | SciPy constants (CODATA 2022) | 10 | 5.6e-12 (NUCLEAR_MAGNETON) |
math | mpmath, 40 digits | 42 | 2.7e-16 (Z_90) |
physics | SciPy constants (CODATA 2022) | 28 | 1.9e-11 (CLASSICAL_ELECTRON_RADIUS) |
units | SciPy constants (CODATA 2022) | 8 | 1.5e-16 (HORSEPOWER) |
The physical differences are those between constants derived from the exact definitions and CODATA’s separately adjusted values, well inside CODATA’s uncertainties (the Bohr radius, for example, is known to ).
CODATA constants by name
The codata module is SciPy’s scipy.constants.physical_constants table. It holds every recommended value of the CODATA 2022 adjustment with its unit and standard uncertainty, looked up by its official name:
physical_constant("electron mass")returns aPhysicalConstantwith value , unitkgand uncertainty ;value,unitandprecision(the relative uncertainty) return one field;find("magnetic moment")lists the matching names.
Like SciPy’s, the table also keeps 90 names from earlier adjustments, such as "mag. constant" for what CODATA now calls the vacuum magnetic permeability. These are marked obsolete and left out of find.
The table is generated from SciPy’s by book/generator/data/make_codata.py, and the comparison doubles as an audit of the hand-written constants above:
/// One entry of the CODATA table: SciPy's `physical_constants[name]` as a record.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct PhysicalConstant {
/// The name as CODATA spells it, e.g. `"electron mass"`.
pub name: &'static str,
/// The recommended value, in `unit`.
pub value: f64,
/// The SI unit, e.g. `"kg"` or `"J T^-1"`; empty for dimensionless constants.
pub unit: &'static str,
/// The standard (one-sigma) absolute uncertainty; 0 for exact constants.
pub uncertainty: f64,
/// Whether the name comes from an earlier CODATA adjustment and is no longer current.
pub obsolete: bool,
}
impl PhysicalConstant {
/// The relative uncertainty `uncertainty / |value|` (SciPy's `precision`, which divides by
/// the signed value).
pub fn precision(&self) -> f64 {
self.uncertainty / self.value.abs()
}
/// Whether the value is exact by definition (zero uncertainty).
pub fn is_exact(&self) -> bool {
self.uncertainty == 0.0
}
}
fn entry(row: &'static (&'static str, f64, &'static str, f64, bool)) -> PhysicalConstant {
PhysicalConstant { name: row.0, value: row.1, unit: row.2, uncertainty: row.3, obsolete: row.4 }
}
/// The constant called `name` (exact, case-sensitive match), or `None`.
pub fn physical_constant(name: &str) -> Option<PhysicalConstant> {
TABLE.iter().find(|r| r.0 == name).map(entry)
}
/// The value of the constant called `name` (SciPy's `value`).
pub fn value(name: &str) -> Option<f64> {
physical_constant(name).map(|c| c.value)
}
/// The unit of the constant called `name` (SciPy's `unit`).
pub fn unit(name: &str) -> Option<&'static str> {
physical_constant(name).map(|c| c.unit)
}
/// The relative uncertainty of the constant called `name`.
pub fn precision(name: &str) -> Option<f64> {
physical_constant(name).map(|c| c.precision())
}
/// The names of the current (CODATA 2022) constants that contain `sub`, ignoring case, in
/// sorted order (SciPy's `find`). An empty `sub` lists them all.
pub fn find(sub: &str) -> Vec<&'static str> {
let sub = sub.to_lowercase();
let mut out: Vec<&'static str> = TABLE.iter().filter(|r| !r.4 && r.0.to_lowercase().contains(&sub)).map(|r| r.0).collect();
out.sort_unstable();
out
}
/// Every entry of the table, current and obsolete, in SciPy's order.
pub fn all() -> impl Iterator<Item = PhysicalConstant> {
TABLE.iter().map(entry)
}
Table 26.2. The CODATA table and the hand-written constants against SciPy.
| Check | Result against SciPy 1.17.1 (CODATA 2022) |
|---|---|
physical_constant: values and uncertainties of all 445 entries | identical |
find: “”, “radius”, “magn”, “electron”, “Planck” (number of names) | identical (355, 5, 29, 54, 11) |
The library’s 46 hand-written constants (physics, em) against the table | 46 of 46 within the CODATA uncertainty; largest relative difference 2e-11 (classical electron radius) |
The audit found two hand-written constants outside their uncertainty. The Rydberg constant and the Hartree energy had been computed from with the rounded and , which put them about off, ten times CODATA’s uncertainty for . Since 2.15.0 both are CODATA’s values. The largest remaining difference, for the classical electron radius, is well inside its uncertainty of .
Machine epsilon and ULPs
A double-precision number has a 53-bit significand. Its neighbours are therefore apart, where : the unit in the last place. The relative spacing lies between and , the machine epsilon, whatever the magnitude:
Figure 26.1. ULP.
Measured by halving until rounds to 1, the machine epsilon is 2.220446049250313e-16, equal to f64::EPSILON = : true.
Comparing results by the number of representable numbers between them, rather than by a fixed tolerance, adapts to their magnitude. Mapping the bit patterns of IEEE doubles onto a line of integers makes that count a subtraction:
pub fn ulps_between(a: f64, b: f64) -> Option<u64> {
if a.is_nan() || b.is_nan() {
return None;
}
// Map the bit patterns onto a monotonic integer line.
let key = |v: f64| {
let bits = v.to_bits() as i64;
if bits < 0 { i64::MIN - bits } else { bits }
};
Some(key(a).abs_diff(key(b)))
}
Unit conversion
Each unit has a dimension, a scale to its SI base unit and, for temperatures, an offset. Converting goes through the base unit, , and units of different dimensions are refused. Symbols are matched exactly first and then, if that is unambiguous, ignoring case. Ignoring case blindly would make mW a megawatt and kb a kilobyte, so ambiguous spellings such as mw are refused.
Table 26.3. Unit conversions against exact values.
| conversion | library | exact |
|---|---|---|
| 1 mi in km | 1.609344 | 1.609344 (exact) |
| 100 km/h in mph | 62.1371192237334 | 62.137119223733… |
| 1 atm in psi | 14.69594877551345 | 14.695948775513… |
| 98.6 F in C | 37 | 37 |
| 1 GiB in MB | 1073.741824 | 1073.741824 |
| 1 mW in W | 0.001 | 0.001 |
| 1 MW in W | 1000000 | 1 000 000 |
| 760 torr in atm | 1 | 1 (exact) |
| 1 mw in W | error: Ambiguous unit: give its case-sensitive symbol, such as mW or MW. | ambiguous: milli- or mega- |
Terminal plots
Each character cell of a Braille plot holds a 2×4 grid of dots, so a 60×16-character plot has 120×64 addressable points. Curves are drawn by joining successive points with line segments in dot space. Axes carry minimum, middle and maximum labels, and several series are told apart by a legend and, optionally, ANSI colours. The polar version draws antenna patterns in dB with rings every few dB.
Algorithm
The ULP of : take the bit pattern of as an integer, add 1 to obtain the next representable number, convert back, and subtract .
The distance in ULPs between two numbers. The bit patterns of positive doubles, read as integers, increase with the numbers themselves, but those of negative doubles run the other way, because the sign is a separate bit.
- Read each number’s bits as a signed 64-bit integer.
- If the integer is negative, replace it by the most negative integer minus itself. The integers now increase with the numbers across the whole range, with and mapped to the same value.
- Return the absolute difference of the two integers: the number of representable numbers between the two.
Unit conversion of a value:
- look up both unit symbols, first exactly, then ignoring case if that gives a single match;
- check that the two units measure the same dimension;
- convert to the base unit, , and from it to the target, subtracting and dividing by .
Braille plot: each character cell of the terminal holds a grid of dots.
- Scale the data to dot coordinates, for a canvas of twice the width and four times the height in characters.
- Draw each line segment by setting the dots along it.
- For each character cell, collect its eight dots into the bit pattern that selects the corresponding Braille character.
- Add the axes, tick labels and legend as ordinary text.
Implementation
- Constants are
f64throughout, with SI units unless the name says otherwise (_DB,_HZ, …); the constants module uses onlycore, so it also suitsno_stdcode. - Most
ErrorsJSLvariants carry&'static strmessages, so errors are cheap and allocation-free;MessageandLinearAlgebracarry aStringfor messages built at run time. ErrorsJSLimplementsDisplayandstd::error::Error, converts fromStringand from the linear-algebra crate’sLinalgError, and is#[non_exhaustive]: amatchon it needs a wildcard arm.
In practice
//! Constants, floating-point spacing, unit conversion and a terminal plot.
use lib_jsl_core::constants::{em, math, physics};
use lib_jsl_utils::machine_epsilon::{approx_eq_ulps, ulp, ulps_between};
use lib_jsl_utils::terminal_plot::{PlotOptions, PlotSeries, render_terminal_plot};
use lib_jsl_utils::unit_conversion::{unit_conversion, watts_to_dbm};
fn main() {
// Constants are plain f64 values grouped by field.
println!("wavelength of 2.4 GHz: {:.4} m", physics::C / 2.4e9);
println!("free-space impedance: {:.6} ohm, Euler's gamma {}", em::Z_0, math::EULER_GAMMA);
// Floating-point spacing: 0.1 + 0.2 is one step away from 0.3.
println!("ulp(1) = {:e}, ulp(1e6) = {:e}", ulp(1.0), ulp(1e6));
println!("0.1 + 0.2 is {:?} representable steps from 0.3; equal within 1 ulp: {}", ulps_between(0.1 + 0.2, 0.3), approx_eq_ulps(0.1 + 0.2, 0.3, 1));
// Unit conversion checks dimensions and respects case where prefixes need it.
println!("55 mph = {:.2} km/h; 20 C = {:.1} F", unit_conversion(55.0, "mph", "km/h").unwrap(), unit_conversion(20.0, "C", "F").unwrap());
println!("25 mW = {:.2} dBm; converting kg to m is refused: {}", watts_to_dbm(unit_conversion(25.0, "mW", "W").unwrap()), unit_conversion(1.0, "kg", "m").is_err());
// A damped oscillation drawn with Braille dots.
let t: Vec<f64> = (0..400).map(|i| i as f64 * 0.05).collect();
let y: Vec<f64> = t.iter().map(|&t| (-0.15 * t).exp() * (2.0 * t).cos()).collect();
let envelope: Vec<f64> = t.iter().map(|&t| (-0.15 * t).exp()).collect();
let options = PlotOptions { width: 56, height: 10, title: Some("damped oscillation".into()), ..Default::default() };
println!("{}", render_terminal_plot(&[PlotSeries { label: "signal", x: &t, y: &y }, PlotSeries { label: "envelope", x: &t, y: &envelope }], &options));
}
wavelength of 2.4 GHz: 0.1249 m
free-space impedance: 376.730313 ohm, Euler's gamma 0.5772156649015329
ulp(1) = 2.220446049250313e-16, ulp(1e6) = 1.1641532182693481e-10
0.1 + 0.2 is Some(1) representable steps from 0.3; equal within 1 ulp: true
55 mph = 88.51 km/h; 20 C = 68.0 F
25 mW = 13.98 dBm; converting kg to m is refused: true
damped oscillation
1 │⢹⠲⢄⡀
│ ⡇ ⠈⠑⠲⢤⣀⡀
│ ⢸ ⡏⢳⠲⠤⣄⣀⡀
│ ⢸ ⡸ ⠈⡆ ⠉⠉⢲⠖⣦⠤⢤⣀⣀⡀
│ ⡇ ⡇ ⢸ ⢀⠎ ⠈⡆ ⠉⢉⡝⠛⢶⠒⠒⠢⠤⠤⠤⣤⣄⣀⣀⣀⣀⣀⣀⡀
0.1041 │ ⢇ ⢸ ⠈⡆ ⡸ ⠘⡄ ⢀⡎ ⢣⡀ ⣠⠎ ⠙⢦⡀ ⢀⡴⠛⠉⠉⠛⢭⣉⣉⣩⠽⠛⠛⠒⠲⠶
│ ⢸ ⡸ ⢱ ⢠⠃ ⢱⡀⢀⡞ ⠑⠦⠞⠁ ⠉⠉⠉
│ ⠈⡆ ⢀⠇ ⠈⣆⢀⡎ ⠉⠉
│ ⢇ ⢸ ⠈⠋
-0.7919 │ ⠘⣤⠃
└────────────────────────────────────────────────────────
0 9.975 19.95
1 signal
2 envelope
Strengths
- One error type and one set of numeric traits across the workspace.
- Constants checked against independent references, with exact values exact.
- Unit conversion that refuses dimension errors and ambiguous prefixes.
Weaknesses
- Unit conversion has a fixed table: no compound units (such as N·m) and no SI prefixes on arbitrary units.
- Error messages are fixed strings, without the values that caused them.
Exercises
- Show that lies in for normal doubles, and explain the sawtooth in the figure.
- Show that in double precision, and that they differ by one ulp.
- Derive the Bohr radius from the exact SI constants and , and estimate its uncertainty from that of .
- Explain why temperature conversion needs an offset, and why converting temperature differences must not use it.
- Count the dots in a Braille cell and design the bit layout for a 2×4 grid.
Hints and answers
- for , so ; the ratio is largest just above each power of two and falls to half that just below the next, a sawtooth.
- in double precision, which differs from (stored as ) by , one ulp at that magnitude.
- ; its relative uncertainty combines those of and (the SI constants and are exact), and is dominated by , about .
- Celsius to kelvin has an offset, because the scales have different zero points; a temperature difference of 1 °C equals 1 K, with no offset, since the offset cancels in a difference.
- A Braille cell has 6 or 8 dots: the Unicode block uses 8, with dot 1–8 mapped to bits 0–7 (offset ).
Further reading
- E. Tiesinga, P. J. Mohr, D. B. Newell and B. N. Taylor, “CODATA recommended values of the fundamental physical constants: 2018”, Reviews of Modern Physics 93 (2021) 025010; and the 2022 adjustment at physics.nist.gov/constants.
- D. Goldberg, “What every computer scientist should know about floating-point arithmetic”, ACM Computing Surveys 23 (1991) 5–48.
- IEEE Standard for Floating-Point Arithmetic, IEEE 754-2019.
- A. Thompson and B. N. Taylor, Guide for the Use of the International System of Units (SI), NIST Special Publication 811, 2008.