Programming Search⌘K

Conceptcore

Units of measure

Also called units of measure, units of measurement, physical units, dimensional analysis, dimension types, quantity types, unit types, units in types.

A unit type attaches a unit, such as metres or seconds, to a number. The compiler or the library then rejects sums of different units and works out the unit of each product and quotient.

Applies to
core-languages

Idea

A number in a program usually has a unit, such as metres, seconds or bytes, but the language sees only the number. A unit type attaches the unit to the value, so that the compiler or a library can check the arithmetic. Two rules come from physics. Values can be added, subtracted and compared only when they have the same dimension, such as length or time. Multiplication and division combine dimensions, so a length divided by a time is a speed. A unit system also converts between units of one dimension, such as feet and metres, at one place in the code. Without these checks, a value in one unit can reach code that expects another, and the program gives a wrong answer with no error.

from fractions import Fraction

BASE = ("m", "kg", "s")  # length, mass, time: the exponents form the dimension


class Q:  # a quantity: a value in SI base units, with a dimension
    def __init__(self, value, dim):
        self.value, self.dim = value, tuple(dim)

    def __add__(self, other):  # only quantities of one dimension can be added
        if self.dim != other.dim:
            raise TypeError(f"cannot add {unit(self.dim)} and {unit(other.dim)}")
        return Q(self.value + other.value, self.dim)

    def __mul__(self, other):  # multiplying adds the exponents
        return Q(self.value * other.value, map(sum, zip(self.dim, other.dim)))

    def __truediv__(self, other):  # dividing subtracts them
        return Q(self.value / other.value,
                 (a - b for a, b in zip(self.dim, other.dim)))

    def __repr__(self):
        return f"{float(self.value):g} {unit(self.dim)}"


def unit(dim):
    return " ".join(b if e == 1 else f"{b}^{e}" for b, e in zip(BASE, dim) if e) or "1"


metre, kilogram, second = Q(1, (1, 0, 0)), Q(1, (0, 1, 0)), Q(1, (0, 0, 1))
newton = kilogram * metre / (second * second)
pound_force = Q(Fraction(44482216152605, 10**13), newton.dim)  # 4.4482... N

distance, time = Q(100, metre.dim), Q(Fraction(958, 100), second.dim)
print("speed:", distance / time)
accel = Q(2, (metre / (second * second)).dim)
print("force:", Q(3, kilogram.dim) * accel, "=", (Q(3, kilogram.dim) * accel).value, "N")
print("10 lbf s in N s:", Q(10, (0, 0, 0)) * pound_force * second)
try:
    distance + time
except TypeError as err:
    print("TypeError:", err)

impulse = 10  # a bare number: lbf s for one team, N s for the other
print(f"read as N s: {impulse} N s, error factor {float(pound_force.value):.2f}")
Output
speed: 10.4384 m s^-1
force: 6 m kg s^-2 = 6 N
10 lbf s in N s: 44.4822 m kg s^-1
TypeError: cannot add m and s
read as N s: 10 N s, error factor 4.45

Each quantity stores its value in base units and its dimension as a tuple of exponents of metres, kilograms and seconds. Division subtracts the exponents, so 100 metres in 9.58 seconds gives metres per second, and a newton is the derived unit kg m s^-2. Adding a length to a time raises an error. The last line shows the error that a bare number permits: an impulse in pound-force seconds read as newton-seconds is wrong by a factor of 4.45, with no error from the program.

How it works

Dimensions and units. A dimension is a kind of quantity, such as length, mass or time, and a unit is one scale for it, such as the metre or the foot. The SI defines seven base dimensions, and every other dimension is a product of powers of them: speed is length to the power 1 and time to the power -1. A unit system stores the exponents for each value, as the example does at run time, or in the type, where the compiler checks them. Addition needs equal exponents, multiplication adds them, and division subtracts them. A quantity with all exponents zero, such as a ratio of two lengths, is a plain number.

Units in the type system. F# has units of measure in the language: "By using quantities with units, you enable the compiler to verify that arithmetic relationships have the correct units, which helps prevent programming errors."1 The compiler infers units like it infers types, so a function that divides its arguments gets a type such as float<'a> -> float<'b> -> float<'a/'b>, generic over units. The check costs nothing when the program runs: "the units of measure are eliminated, so the units are lost at run time".1 Languages without this feature encode the exponents in generic types, as C++ templates and Rust traits do, or write one type per unit.

One type per unit. The simplest form gives each unit its own type, such as a Metres struct or a named type in Go, and defines only the operations that make sense. The compiler then rejects a Feet where a Metres is expected, and each conversion is a named function. This form is easy to read, but each product and quotient needs its own type and operator, and generic code over all units is hard to write.

Time in standard libraries. Most standard libraries have a unit type for durations, the most common unit in programs. C++'s std::chrono::duration puts the unit in the type: "the tick period is a compile-time rational fraction representing the time in seconds from one tick to the next".2 Go's time package says that "A Duration represents the elapsed time between two instants as an int64 nanosecond count".3 Rust's Duration is "A Duration type to represent a span of time, typically used for system timeouts",4 Java's Duration is "A time-based amount of time, such as '34.5 seconds'",5 and in Python "A timedelta object represents a duration, the difference between two datetime or date instances".6 An API that takes one of these types, not a bare number of seconds or milliseconds, cannot be called with the wrong unit.

Units in CSS. CSS is one of the few languages in wide use with units in the language. Lengths, times and angles are dimensions, such as 10px, 2s and 45deg, and calc() checks their types. The specification gives the rule for sums: "At a + or - sub-expression, attempt to add the types of the left and right arguments. If this returns failure, the entire calculation’s type is failure."7 So calc(1px + 2s) is invalid, while a length divided by a length gives a number.

Conversions and scale. A unit system converts at the edges of a program, where values are read and written, and keeps one unit inside. Most libraries store each value in a base unit, as the example and the JavaScript file do, so a conversion is one multiplication. Others, such as std::chrono, keep the unit in the type and convert when two units meet, which avoids rounding when all values are integers.

In languages

LanguageVerdictNote
PythonLibrary
C++Library
JavaLibrary
CIdiom
C#Library
JavaScriptIdiom
TypeScriptIdiomBranded number types, a number type joined with a unique marker type, keep units apart at compile time, but no example file exists.
GoIdiom
RustLibrary
KotlinIdiomKotlin.time.Duration is the unit type for time, and value classes keep other units apart with no run-time cost, but no example file exists because kotlinc is not installed.
SQLIdiomINTERVAL types hold durations, and the difference of two timestamps is an interval; other units are stored as plain numbers, but no example file exists.
BashDoes not applyBash values are strings, and units appear only in names and in the options of commands such as sleep.
PowerShellIdiomThe numeric suffixes KB, MB, GB, TB and PB multiply a number into bytes, and TimeSpan holds durations, but no example file exists because pwsh is not installed.
HTMLDoes not applyHTML attributes such as width take numbers whose unit the specification fixes.
CSSNativeLengths, times, angles and resolutions are dimensions with units, and calc() checks the types of its arguments, but no example file exists.
Regular expressionsDoes not applyRegular expressions have no values with units.
Language Verdict Mechanism
Python library timedelta for time; Pint and Astropy for physical units
JavaScript idiom one base unit per class; Intl.NumberFormat units for output only
TypeScript idiom branded number types
Java library java.time.Duration; JSR 385 and Indriya
Kotlin idiom kotlin.time.Duration; value classes per unit
C# library TimeSpan; record structs with operators; UnitsNet
Go idiom time.Duration; named types per unit
Rust library std::time::Duration; newtypes; the uom crate
C idiom one struct per unit, or the unit in the name
C++ library std::chrono ratios; dimension templates; mp-units
Bash n/a values are strings
PowerShell idiom KB, MB and GB suffixes; TimeSpan
SQL idiom INTERVAL types; units in column names
Regex n/a no values with units
HTML n/a attributes with fixed units
CSS native dimensions such as px, s and deg, checked in calc()

No core general-purpose language checks physical dimensions in the language, as F# does, so the verdicts are library or idiom. Each one has a unit type for time in its standard library, and Python, Java, C#, Rust and C++ have widely used libraries for physical quantities. CSS is native: units are part of its values, and its math functions check dimensions.

The example files show three forms. Python, Java, C#, Go, Rust and C++ use the standard type for durations, and the Go file shows a limit: Go's Duration does not track dimensions, so a duration divided by a duration prints as 4ns. C#, Go, Rust and C use one type per unit, and their fails blocks show the compiler rejecting a sum of different units. The C++ file encodes the exponents in template parameters, as the idea block does at run time. The C file also shows the common unchecked form, a plain number with the unit in its name.

PythonGitHub
from datetime import timedelta
from typing import NewType

Metres = NewType("Metres", float)
Feet = NewType("Feet", float)


def climb(altitude: Metres, by: Metres) -> Metres:
    return Metres(altitude + by)


timeout = timedelta(seconds=90) + timedelta(milliseconds=500)
print(timeout, "is", timeout.total_seconds(), "seconds")
print("2 min / 30 s =", timedelta(minutes=2) / timedelta(seconds=30))
try:
    timeout + 5
except TypeError as err:
    print("TypeError:", err)

# mypy rejects the Feet argument, but at run time a NewType is a plain float
print("climb:", climb(Metres(1000.0), Feet(500.0)), type(Feet(500.0)).__name__)
Output
0:01:30.500000 is 90.5 seconds
2 min / 30 s = 4.0
TypeError: unsupported operand type(s) for +: 'datetime.timedelta' and 'int'
climb: 1500.0 float
  • Verdict: library. The standard library has a unit type only for time: timedelta stores a duration, adds only to other durations and dates, and a duration divided by a duration is a plain number. NewType gives a distinct name that mypy checks, but at run time Feet(500.0) is a float, so the wrong call runs. For physical units in general, the Pint library tracks units and dimensions at run time, and Astropy has a units module.
#include <chrono>
#include <iostream>

// A quantity whose type holds the exponents of length (L) and time (T)
template <int L, int T>
struct Q {
    double v;
};
template <int L, int T>
Q<L, T> operator+(Q<L, T> a, Q<L, T> b) { return {a.v + b.v}; }
template <int L1, int T1, int L2, int T2>
Q<L1 - L2, T1 - T2> operator/(Q<L1, T1> a, Q<L2, T2> b) { return {a.v / b.v}; }

using Metres = Q<1, 0>;
using Seconds = Q<0, 1>;
using MetresPerSecond = Q<1, -1>;

int main() {
    using namespace std::chrono;
    using namespace std::chrono_literals;
    auto timeout = 90s + 500ms;  // the type is milliseconds, chosen at compile time
    std::cout << timeout.count() << " ms = " << duration<double>(timeout).count() << " s\n";
    std::cout << "2 min / 30 s = " << 2min / 30s << "\n";
    std::cout << "truncated to seconds: " << duration_cast<seconds>(timeout).count() << "\n";

    MetresPerSecond v = (Metres{5000} + Metres{304.8}) / Seconds{1800};
    std::cout << "speed " << v.v << " m/s, sizeof " << sizeof v << " bytes\n";
}
Output
90500 ms = 90.5 s
2 min / 30 s = 4
truncated to seconds: 90
speed 2.94711 m/s, sizeof 8 bytes

This code does not compile, on purpose.

template <int L, int T>
struct Q {
    double v;
};
template <int L, int T>
Q<L, T> operator+(Q<L, T> a, Q<L, T> b) { return {a.v + b.v}; }

using Metres = Q<1, 0>;
using Seconds = Q<0, 1>;

int main() {
    auto total = Metres{100} + Seconds{9.58};
    return static_cast<int>(total.v);
}
  • Verdict: library. std::chrono::duration puts the unit of time in the type as a compile-time ratio, so 90s + 500ms has the type of milliseconds and converts without loss, while duration_cast makes a lossy conversion explicit. Templates with integer parameters for the exponents of each dimension check physical units at compile time: Q<1, 0> / Q<0, 1> has the type Q<1, -1>, and the value is a single double. The fails block adds metres and seconds, and no operator+ matches. The mp-units library, proposed for a future C++ standard, and Boost.Units do this for all SI quantities.
JavaGitHub
import java.time.Duration;
import java.time.temporal.ChronoUnit;

public class Main {
    record Metres(double value) {
        Metres plus(Metres o) { return new Metres(value + o.value); }
    }

    record Feet(double value) {
        Metres toMetres() { return new Metres(value * 0.3048); }
    }

    static Metres climb(Metres altitude, Metres by) { return altitude.plus(by); }

    public static void main(String[] args) {
        Duration timeout = Duration.ofSeconds(90).plusMillis(500);
        System.out.println(timeout + " = " + timeout.toMillis() + " ms");
        System.out.println("2 min / 30 s = " + Duration.ofMinutes(2).dividedBy(Duration.ofSeconds(30)));
        System.out.println("one day in hours: " + ChronoUnit.DAYS.getDuration().toHours());
        // climb(new Metres(1000), new Feet(500)) does not compile
        System.out.println(climb(new Metres(1000), new Feet(500).toMetres()));
    }
}
Output
PT1M30.5S = 90500 ms
2 min / 30 s = 4
one day in hours: 24
Metres[value=1152.4]
  • Verdict: library. java.time.Duration is a unit type for time in the standard library, and ChronoUnit names the units. For other quantities, a record per unit makes the compiler reject a Feet where a Metres is expected, and the conversion is an explicit method. The Units of Measurement API, JSR 385, with the Indriya implementation, gives general quantities and dimensions.
#include <stdio.h>

/* One struct per unit: the compiler rejects a feet value where metres
   are expected, because the two struct types are different. */
typedef struct { double v; } metres;
typedef struct { double v; } feet;
typedef struct { double v; } seconds;

static metres from_feet(feet f) { return (metres){f.v * 0.3048}; }
static metres add_m(metres a, metres b) { return (metres){a.v + b.v}; }
static double speed_mps(metres d, seconds t) { return d.v / t.v; }

/* The common C idiom instead: plain numbers with the unit in the name */
static void set_timeout_ms(long timeout_ms) { printf("timeout %ld ms\n", timeout_ms); }

int main(void) {
    metres trip = add_m((metres){5000}, from_feet((feet){1000}));
    printf("trip %.1f m, speed %.3f m/s\n", trip.v, speed_mps(trip, (seconds){1800}));
    long timeout_s = 30;
    set_timeout_ms(timeout_s * 1000);
    set_timeout_ms(timeout_s); /* compiles: the name is only a convention */
    return 0;
}
Output
trip 5304.8 m, speed 2.947 m/s
timeout 30000 ms
timeout 30 ms
  • Verdict: idiom. C has no units. A struct per unit makes the compiler reject one unit where another is expected, at the cost of a function for each operation, because C has no operator overloading. The common idiom is a plain number with the unit in its name, such as timeout_ms, which nothing checks: the second call passes seconds where milliseconds are expected.
using System;

var timeout = TimeSpan.FromSeconds(90) + TimeSpan.FromMilliseconds(500);
Console.WriteLine($"{timeout} = {timeout.TotalMilliseconds} ms");
Console.WriteLine($"2 min / 30 s = {TimeSpan.FromMinutes(2) / TimeSpan.FromSeconds(30)}");

var trip = new Metres(5000) + new Feet(1000).ToMetres();
var speed = trip / new Seconds(1800);
Console.WriteLine($"{trip}, {speed}");

readonly record struct Metres(double Value)
{
    public static Metres operator +(Metres a, Metres b) => new(a.Value + b.Value);
    public static MetresPerSecond operator /(Metres d, Seconds t) => new(d.Value / t.Value);
    public override string ToString() => $"{Value:0.##} m";
}

readonly record struct Feet(double Value)
{
    public Metres ToMetres() => new(Value * 0.3048);
}

readonly record struct Seconds(double Value);

readonly record struct MetresPerSecond(double Value)
{
    public override string ToString() => $"{Value:0.###} m/s";
}
Output
00:01:30.5000000 = 90500 ms
2 min / 30 s = 4
5304.8 m, 2.947 m/s

This code does not compile, on purpose.

using System;

var height = new Metres(1000) + new Feet(500);
Console.WriteLine(height);

readonly record struct Metres(double Value)
{
    public static Metres operator +(Metres a, Metres b) => new(a.Value + b.Value);
}

readonly record struct Feet(double Value);
  • Verdict: library. TimeSpan is the unit type for time. Record structs with operators model other units: Metres / Seconds gives MetresPerSecond, because the operator says so, and the structs cost no more than a double. The fails block adds Metres and Feet, and the compiler reports CS0019 because no + operator takes both. The UnitsNet library defines several thousand units in this style.
JavaScriptGitHub
// Store every length in metres, and convert only at the edges
const UNIT = { m: 1, km: 1000, ft: 0.3048, mi: 1609.344 };

class Length {
  #metres;
  constructor(metres) { this.#metres = metres; }
  static of(value, unit) {
    if (!(unit in UNIT)) throw new RangeError(`unknown length unit ${unit}`);
    return new Length(value * UNIT[unit]);
  }
  plus(other) {
    if (!(other instanceof Length)) throw new TypeError("can only add a Length");
    return new Length(this.#metres + other.#metres);
  }
  in(unit) { return this.#metres / UNIT[unit]; }
}

const run = Length.of(5, "km").plus(Length.of(1, "mi"));
console.log(`${run.in("km").toFixed(3)} km = ${run.in("mi").toFixed(3)} mi`);
for (const bad of [() => run.plus(300), () => Length.of(3, "furlong")]) {
  try {
    bad();
  } catch (err) {
    console.log(`${err.name}: ${err.message}`);
  }
}
const fmt = new Intl.NumberFormat("en", { style: "unit", unit: "kilometer-per-hour" });
console.log(fmt.format(run.in("km") / 0.5));
Output
6.609 km = 4.107 mi
TypeError: can only add a Length
RangeError: unknown length unit furlong
13.219 km/h
  • Verdict: idiom. JavaScript numbers carry no unit. The usual idiom stores each quantity in one base unit, here metres in a private field, and converts only when a value enters or leaves the program. The class rejects a bare number and an unknown unit at run time. Intl.NumberFormat with style: "unit" formats a value with a unit, but it does not check units.
package main

import (
	"fmt"
	"time"
)

type Metres float64
type Feet float64

func (f Feet) Metres() Metres { return Metres(f * 0.3048) }

func climb(altitude, by Metres) Metres { return altitude + by }

func main() {
	timeout := 90*time.Second + 500*time.Millisecond
	fmt.Println(timeout, "=", timeout.Milliseconds(), "ms")
	fmt.Println("2m / 30s as Duration:", (2*time.Minute)/(30*time.Second))
	fmt.Println("2m / 30s as a number:", (2*time.Minute).Seconds()/(30*time.Second).Seconds())
	retries := 3
	fmt.Println("total wait:", time.Duration(retries)*timeout)
	fmt.Println("climb:", climb(1000, Feet(500).Metres()))
}
Output
1m30.5s = 90500 ms
2m / 30s as Duration: 4ns
2m / 30s as a number: 4
total wait: 4m31.5s
climb: 1152.4

This code does not compile, on purpose.

package main

import (
	"fmt"
	"time"
)

func main() {
	retries := 3
	timeout := 2 * time.Second
	fmt.Println(retries * timeout)
}
  • Verdict: idiom. time.Duration is a named type for an int64 count of nanoseconds, and the constants such as time.Second give it units. The fails block multiplies an int variable by a Duration, and the compiler rejects the mismatched types; the fix is time.Duration(retries) * timeout. The type does not track dimensions: a Duration divided by a Duration is still a Duration, so the run block prints 4ns where the answer is the number 4. Named types such as Metres and Feet keep units apart in the same way.
RustGitHub
use std::ops::{Add, Div};
use std::time::Duration;

#[derive(Debug, Clone, Copy, PartialEq)]
struct Metres(f64);
#[derive(Debug, Clone, Copy, PartialEq)]
struct Seconds(f64);
#[derive(Debug, Clone, Copy, PartialEq)]
struct MetresPerSecond(f64);

impl Add for Metres {
    type Output = Metres;
    fn add(self, o: Metres) -> Metres { Metres(self.0 + o.0) }
}

impl Div<Seconds> for Metres {
    type Output = MetresPerSecond;
    fn div(self, t: Seconds) -> MetresPerSecond { MetresPerSecond(self.0 / t.0) }
}

fn main() {
    let timeout = Duration::from_secs(90) + Duration::from_millis(500);
    println!("{:?} = {} ms", timeout, timeout.as_millis());
    println!("2 min / 30 s = {}", Duration::from_secs(120).div_duration_f64(Duration::from_secs(30)));
    let trip = Metres(5000.0) + Metres(304.8);
    println!("{:?} / {:?} = {:?}", trip, Seconds(1800.0), trip / Seconds(1800.0));
    println!("checked_sub: {:?}", Duration::from_secs(1).checked_sub(timeout));
}
Output
90.5s = 90500 ms
2 min / 30 s = 4
Metres(5304.8) / Seconds(1800.0) = MetresPerSecond(2.947111111111111)
checked_sub: None

This code does not compile, on purpose. The error is E0308.

use std::ops::Add;

struct Metres(f64);
struct Seconds(f64);

impl Add for Metres {
    type Output = Metres;
    fn add(self, o: Metres) -> Metres { Metres(self.0 + o.0) }
}

fn main() {
    let total = Metres(100.0) + Seconds(9.58);
    println!("{}", total.0);
}
  • Verdict: library. std::time::Duration is the unit type for time; it cannot be negative, so checked_sub returns None for a negative result. Newtypes with Add and Div implementations give each unit its own type and state which products and quotients exist. The fails block adds Metres and Seconds, and the compiler reports E0308. The uom crate checks dimensions for all SI quantities at compile time with no run-time cost.
  • Unit inference. F# infers units for functions with no annotations and makes functions generic over units. Andrew Kennedy's work showed that this inference works like ordinary type inference.
  • Run-time quantities. Pint, Astropy and UnitsNet store the unit with each value and check it during arithmetic. They are simpler to use with data from files, at a cost in speed and memory.
  • Affine units. Temperatures in Celsius and Fahrenheit, positions in time and dates have an offset: two temperatures cannot be added, but a temperature and a difference can. std::chrono separates time_point from duration for this reason. See measure elapsed time.
  • Information units. Bytes, bits and pixels are not SI units, and systems such as mp-units define them as separate dimensions.
  • Angles and dimensionless quantities. Radians, ratios and percentages have no dimension, so a dimension check cannot tell them apart. Some libraries treat angles as a separate kind.
  • Money. A currency acts like a unit: amounts in two currencies cannot be added without a conversion rate, and the rate changes over time.
  • Refinement types. A unit is one kind of fact about a number; dependent and refinement types state others, such as ranges.

Pitfalls

  • Bare numbers at boundaries. Most unit errors happen where one component passes a plain number to another. The Mars Climate Orbiter was lost in 1999 because "software that calculated the total impulse produced by thruster firings produced results in pound-force seconds", and the receiving software expected them "to be in newton-seconds (incorrect by a factor of 4.45)".8 Put the unit in the type of every interface, file format and API, or at least in the name.
  • Timeouts in the wrong unit. An API that takes timeout as a number can be called with seconds where it expects milliseconds, and the program waits 1000 times too long or too short. Take a duration type, as the Go, Rust and Java standard libraries do.
  • Lossy conversions. Converting milliseconds to seconds in integers truncates. std::chrono makes this explicit with duration_cast; in other languages, convert in floating point or keep the smaller unit.
  • Conversion factors written by hand. A factor such as 0.3048 or 4.448 typed in many places can be wrong in one of them. Define each factor once, in the unit system.
  • Dimensionless confusion. A check on dimensions cannot tell radians from degrees, or a ratio from a percentage, because all have dimension one. Name the unit, or use a separate type.
  • Floating-point error. A conversion through a base unit and back can change the last digits of a value. See floating-point arithmetic.

Cost

Units checked at compile time cost nothing when the program runs: F# erases them, and a C++ template quantity or a Rust newtype is a single double in memory, as the C++ file shows. A conversion costs one multiplication, which the compiler can often fold into a constant. Run-time unit libraries store a unit with each value, often a pointer or a small table of exponents, and check and combine units on each operation, which can make numeric code many times slower than plain floats; they also stop vectorized arrays unless the unit is stored once for a whole array, as Pint and Astropy do with NumPy. Compile-time unit libraries can increase compile times and give long error messages.

History

Proposals to add units to programming languages appeared in the 1970s: Narain Gehani described units as a data attribute in 1977, and Michael Karr and David Loveman described the incorporation of units into programming languages in 1978. Andrew Kennedy defined dimension types with inference in 1994, and John Barton and Lee Nackman showed in the same year that C++ templates can check dimensions at compile time. Kennedy later added units of measure to F#, which first shipped them in 2008.1

Standard libraries added types for durations. Python's timedelta arrived with the datetime module in 2003,6 C++11 added std::chrono from Howard Hinnant's design in 2011,2 Go 1.0 shipped time.Duration in 2012,3 Java 8 added java.time in 2014,5 and Rust 1.3 stabilized Duration in 2015.4 Libraries for physical units followed: Boost.Units in 2008, Pint in 2012, JSR 385 for Java in 2019, and mp-units, which is proposed for a future C++ standard. CSS added typed arithmetic with units to calc().7 Accidents kept the topic visible, from the fuel error of an Air Canada flight in 1983, measured in pounds where kilograms were needed, to the loss of the Mars Climate Orbiter in 1999.8

References

  1. Units of Measure, F# language reference, Introduction and Units at Runtime
  2. std::chrono::duration, cppreference.com, Description
  3. Package time, Go standard library documentation, type Duration
  4. Struct Duration, Rust standard library documentation, Description
  5. Class Duration, Java SE 25 API documentation, Class description
  6. datetime, Basic date and time types, Python documentation, timedelta objects
  7. CSS Values and Units Module Level 4, W3C Editor's Draft, Type checking of math functions
  8. Mars Climate Orbiter, Wikipedia, Cause of failure

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/A4Z1BN/text.yaml