units
On this page
Physical quantities with units. A Quantity carries its dimension
(the exponents of the seven SI base quantities) in its type, so a
formula that mixes up a length and a time does not compile, and the
check costs nothing when it runs. Units read at run time go through
DynUnit and Measure, which check the dimension when they run and
throw a UnitError that names both sides.
Values are held in coherent SI units; a unit is a symbol and a scale.
Number suffixes (3km, 20degC) come from literals, the →
conversion and ° from ops; both are features on by default.
Modules
constantsPhysical constants: the seven defining constants of the SI and the exact values derived from them (CODATA 2018, unchanged in 2022), and the measured ones from the CODATA 2022 adjustment.kindsNames for the common dimensions, so signatures read as physics:fn kinetic(m: Mass, v: Velocity) -> Energy.literalsNumber suffixes for the common units:3km,9.81m / 1s / 1s,5kΩ,20degC.opsOperators for unit code (featureops, on by default): q → u the quantity expressed in unitu(level of|) x° degrees as an angle in radians (postfix, level of?) √q square root of a quantity (core's√, always on) Each also has a named form:q.to(u),deg.of(x),q.sqrt().symbolsUnit constants named by their symbols, to import the ones you need:use units::symbols::{km, h, kg, m, s²};.temperatureTemperature readings on the Kelvin, Celsius, Fahrenheit and Rankine scales.unitUnits: the staticUnitof a known dimension (the symbols, what.toand.value_intake) and the dynamicDynUnitthat parsing and unit algebra with run-time exponents give.
Re-exports
temperature::TemperatureSource
pub use temperature::TemperatureTemperatureAn absolute temperature, a reading on any scale.
unit::{DynUnit, Unit}Source
pub use unit::{DynUnit, Unit}Structs
DimSource
pub struct DimA physical dimension: the exponent of each SI base quantity, in the
order length (m), mass (kg), time (s), electric current (A),
thermodynamic temperature (K), amount of substance (mol) and
luminous intensity (cd). Velocity is L T^-1, force M L T^-2.
use units::Dim;
let v = Dim::LENGTH / Dim::TIME;
assert(v.symbol() == "m/s");
assert((v * Dim::MASS / Dim::TIME).symbol() == "N");
assert(Dim::LENGTH.pow(3).name() == "volume");
Exponent of length (metre).
Exponent of mass (kilogram).
Exponent of time (second).
Exponent of electric current (ampere).
Exponent of thermodynamic temperature (kelvin).
Exponent of amount of substance (mole).
Exponent of luminous intensity (candela).
No dimension: a pure number (and angles, which SI counts as 1).
Length,
L.Mass,
M.Time,
T.Electric current,
I.Thermodynamic temperature,
Θ.Amount of substance,
N.Luminous intensity,
J.The dimension with exponents
e, in base-quantity order.nabiuse units::Dim; assert(Dim::of([1, 0, -2, 0, 0, 0, 0]).name() == "acceleration");The seven exponents, in base-quantity order.
nabiuse units::Dim; assert(Dim::MASS.exponents() == [0, 1, 0, 0, 0, 0, 0]);Whether every exponent is zero.
nabiuse units::Dim; assert((Dim::LENGTH / Dim::LENGTH).is_none());The dimension raised to the integer power
n. Exponents beyond thei8range wrap; no physical quantity comes near.nabiuse units::Dim; assert(Dim::TIME.pow(-1).name() == "frequency");The
n-th root, ornonewhen an exponent is not a multiple ofn(the square root of a length has no SI dimension).nabiuse units::Dim; assert(Dim::LENGTH.pow(2).root(2) == Dim::LENGTH); assert(Dim::LENGTH.root(2) == none);The common name of this dimension (
"velocity","energy"), ornonefor one without a usual name.nabiuse units::Dim; assert((Dim::MASS * Dim::LENGTH.pow(2) / Dim::TIME.pow(2)).name() == "energy"); assert(Dim::of([5, 0, 0, 0, 0, 0, 0]).name() == none);The coherent SI unit of this dimension, named derived units first:
"N","J/K","W/(m·K)","m/s²";""when dimensionless.nabiuse units::Dim; let k = Dim::MASS * Dim::LENGTH / Dim::TIME.pow(3) / Dim::TEMPERATURE; assert(k.symbol() == "W/(m·K)"); assert((Dim::LENGTH / Dim::TIME.pow(2)).symbol() == "m/s²");symbolin plain ASCII:"kg*m^2/s^2"style,"ohm"forΩ.Unit::parsereads it back.nabiuse units::Dim; assert((Dim::LENGTH / Dim::TIME.pow(2)).ascii() == "m/s^2");The base-unit form only, no named derived unit:
"kg·m/s²"for a force.nabiuse units::Dim; assert((Dim::MASS * Dim::LENGTH / Dim::TIME.pow(2)).base_symbol() == "kg·m/s²");
Trait implementations 3
impl ops::Mul for Dimimpl ops::Div for Dimimpl Display for Dim
MeasureSource
pub struct MeasureA value in a unit known at run time: 3.5 km/h, 20 degC.
*, / and ** n always work and combine the units; + and -
convert the right side to the left side's unit and give a
Result, an error when the dimensions differ. == is true for
equal SI values of one dimension.
use units::Measure;
let d = try! Measure::parse("12 km");
let t = try! Measure::parse("30 min");
let v = d / t;
assert(((try! v.to_str("km/h")).value - 24.0).abs() < 1e-12);
let total = try! (d + try! Measure::parse("500 m")).get();
assert(total.value == 12.5 && total.unit.symbol == "km");
assert((d + t).is_err());
The number, in
unit.The unit.
valueofunit.nabiuse units::{DynUnit, Measure}; let m = Measure::new(3.0, try! DynUnit::parse("ft")); assert((m.si() - 0.9144).abs() < 1e-15);Parse a number and a unit,
"9.81 m/s^2","20 °C","1e-3 kg"; the space is optional ("5km"). A bare unit counts as one of it.nabiuse units::Measure; assert((try! Measure::parse("9.81 m/s^2")).unit.dim.name() == "acceleration"); assert((try! Measure::parse("2.5e3kg")).si() == 2500.0); assert((try! Measure::parse("km")).si() == 1000.0);The value in coherent SI units.
nabiuse units::Measure; assert((try! Measure::parse("2 h")).si() == 7200.0);The dimension.
nabiuse units::Measure; assert((try! Measure::parse("3 N*m")).dim().name() == "energy");The same quantity in
unit; throws aUnitError::Mismatchthat names both dimensions and the factor between them.nabiuse units::{DynUnit, Measure}; let t = try! Measure::parse("20 degC"); assert((try! t.to(try! DynUnit::parse("degF"))).value == 68.0);towith the unit written as text.nabiuse units::Measure; assert((try! (try! Measure::parse("1 mi")).to_str("km")).value == 1.609344);The same quantity in coherent SI units (
m/s,N,K).nabiuse units::Measure; let p = (try! Measure::parse("1 bar")).to_si_unit(); assert(p.value == 100000.0 && p.unit.symbol == "Pa");
Sourcepub fn fixed<const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32>(§self) throws (UnitError) -> Quantity<f64, L, M, T, I, K, N, J> The static quantity, its dimension given by the expected type; throws a
UnitError::Mismatchwhen it differs.nabiuse units::Measure; use units::kinds::Pressure; let p: Pressure = try! (try! Measure::parse("2 bar")).fixed(); assert(p == 200kPa);The value printed with a format spec chosen at run time, and the unit after it. A spec known when writing the code goes in an f-string,
f"{m:.2}",f"{m:.1e}".nabiuse units::Measure; let m = try! Measure::parse("2 m"); assert(f"{m:.2}" == "2.00 m" && f"{m:.1e}" == "2.0e0 m"); assert(try! m.format(".1e") == "2.0e0 m");Whether the two agree to the relative tolerance
relin SI units; false for different dimensions.nabiuse units::Measure; assert((try! Measure::parse("1 in")).approx_eq(try! Measure::parse("2.54 cm")));
Trait implementations 10
impl Display for Measureimpl PartialEq for Measureimpl ops::Mul for Measureimpl ops::Div for Measureimpl ops::Mul<f64> for Measureimpl ops::Div<f64> for Measureimpl ops::Pow<i32> for Measureimpl ops::Neg for Measureimpl ops::Add for Measureimpl ops::Sub for Measure
QuantitySource
pub struct Quantity<V, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32>A value of a physical quantity, held in coherent SI units (metres,
kilograms, seconds, ...). The seven const parameters are the
exponents of the SI base dimensions, in the order length L, mass
M, time T, electric current I, temperature K, amount N and
luminous intensity J: a velocity is Quantity<f64, 1, 0, -1, 0, 0, 0, 0>, named Velocity in units::kinds.
* and / add and subtract exponents; +, - and the comparisons
take two quantities of one dimension only, so a mismatch does not
compile. V is the value type: f64 (literals and units give it),
f32, Complex<f64> (an impedance), or a core Array<f64, R> for a
whole field of values with the broadcast operators .+ .- .* ./.
use units::kinds::{Length, Time, Velocity};
use units::symbols::{km, h};
fn speed(d: Length, t: Time) -> Velocity { d / t }
let v = speed(42.195km, 2h);
assert(v.value_in(km / h) == 21.0975);
println(v); // 5.860416666666667 m/s
The value in coherent SI units (
3kmholds3000.0).The quantity whose SI value is
value.nabiuse units::Quantity; use units::kinds::Length; let d: Length = Quantity::si(3.0); assert(d == 3m);The dimension, as a value.
nabiassert((3m / 2s).dim().name() == "velocity");The coherent SI unit this quantity prints with:
"m/s","N".nabiassert((2kg * 3m / 1s / 1s).unit_symbol() == "N");The value expressed in
unit, a plain number.nabiuse units::symbols::{mi, ft}; assert(1mi.value_in(ft) == 5280.0);The quantity expressed in
unit, for printing or further dynamic work:3km.to(mi)prints1.8641135767120018 mi. The units must share the dimension, which the types check.nabiuse units::symbols::{mi, km}; let m = 5km.to(mi); assert((m.value - 3.1068559611866697).abs() < 1e-15); assert(m.unit.symbol == "mi");The quantity expressed in the dynamic
unit; throws aUnitError::Mismatchnaming both dimensions when they differ.nabiuse units::DynUnit; let u = try! DynUnit::parse("km/h"); assert((try! (10m / 1s).convert(u)).value == 36.0);The same quantity as a dynamic
Measurein SI units.nabiassert((2m / 1s).measure().unit.symbol == "m/s");The static quantity of a dynamic one, its dimension given by the expected type; throws a
UnitError::Mismatchwhen the measure has another dimension.nabiuse units::{Measure, Quantity}; use units::kinds::Velocity; let v: Velocity = try! Quantity::from_measure(try! Measure::parse("36 km/h")); assert(v == 10m / 1s);
Sourcepub const fn squared(§self) -> Quantity<f64, { 2 * L }, { 2 * M }, { 2 * T }, { 2 * I }, { 2 * K }, { 2 * N }, { 2 * J }> self * self.nabiassert(3m.squared() == 9m²);
Sourcepub const fn cubed(§self) -> Quantity<f64, { 3 * L }, { 3 * M }, { 3 * T }, { 3 * I }, { 3 * K }, { 3 * N }, { 3 * J }> self * self * self.nabiassert(2m.cubed() == 8m³);
Sourcepub const fn inv(§self) -> Quantity<f64, { -L }, { -M }, { -T }, { -I }, { -K }, { -N }, { -J }> 1 / self.nabiassert(2s.inv() == 0.5Hz && 1.0 / 2s == 0.5Hz);
Sourcepub fn powi<const P: i32>(§self) -> Quantity<f64, { L * P }, { M * P }, { T * P }, { I * P }, { K * P }, { N * P }, { J * P }> selfto the integer powerP, given as a const argument so the dimension stays static:x.powi::<3>(). (x ** 3gives a dynamicMeasure, since an operator's operand is a value.)nabiassert(2m.powi::<3>() == 8m³); assert(2m.powi::<-1>().value == 0.5);The absolute value.
nabiassert((-2m).abs() == 2m);
Sourcepub const fn min(§self, other: Quantity<f64, L, M, T, I, K, N, J>) -> Quantity<f64, L, M, T, I, K, N, J> The smaller of two quantities of one dimension.
nabiassert(2m.min(3m) == 2m);
Sourcepub const fn max(§self, other: Quantity<f64, L, M, T, I, K, N, J>) -> Quantity<f64, L, M, T, I, K, N, J> The larger of two quantities of one dimension.
nabiassert(2m.max(3m) == 3m);
Sourcepub fn hypot(§self, other: Quantity<f64, L, M, T, I, K, N, J>) -> Quantity<f64, L, M, T, I, K, N, J> sqrt(self^2 + other^2)without overflow.nabiassert(3m.hypot(4m) == 5m);
Sourcepub fn approx_eq(§self, other: Quantity<f64, L, M, T, I, K, N, J>, rel: f64 = 1e-12, abs: f64 = 0.0) -> bool Whether
selfandotheragree to the relative tolerancerel(and toabsnear zero).nabiassert((0.1m + 0.2m).approx_eq(0.3m));Whether the value is finite (not infinite, not NaN).
nabiassert(1m.is_finite());The value printed with a format spec chosen at run time, and the SI unit after it. A spec known when writing the code goes in an f-string,
f"{q:.3}",f"{q:.2e}".nabilet q = 1m / 3s; assert(f"{q:.3}" == "0.333 m/s" && f"{1500N:.2e}" == "1.50e3 N"); let spec = ".2e"; assert(try! 1500N.format(spec) == "1.50e3 N");The sine of an angle (a dimensionless quantity in radians).
nabiassert(90deg.sin() == 1.0);The cosine of an angle.
nabiassert(0deg.cos() == 1.0);The tangent of an angle.
nabiassert((45deg.tan() - 1.0).abs() < 1e-15);e^self, for a dimensionless exponent ((-E / (k_B * T)).exp()).nabiassert((1J / 1J).exp() == 1.0f64.exp());The natural logarithm of a ratio.
nabiassert((10m / 10m).ln() == 0.0);The cube root, for a quantity whose exponents are all multiples of 3 (a volume); any other is a compile error.
nabiassert(8m³.cbrt() == 2m);The element at
idx, a scalar quantity.nabiuse core::array::Array; use units::symbols::m; assert(m.array(Array::from_list([4.0, 5.0], [2])).at([0]) == 4m);The shape of the values.
nabiuse core::array::Array; use units::symbols::s; let z: Array<f64, 2> = Array::zeros([2, 3]); assert(s.array(z).shape() == [2, 3]);The number of values.
nabiuse core::array::Array; use units::symbols::s; let z: Array<f64, 1> = Array::zeros([4]); assert(s.array(z).len() == 4);The values expressed in
unit, plain numbers (a new array).nabiuse core::array::Array; use units::symbols::{m, cm}; let d = m.array(Array::from_list([1.0, 2.0], [2])); assert(d.values_in(cm).to_list() == [100.0, 200.0]);The sum of all values.
nabiuse core::array::Array; use units::symbols::m; assert(m.array(Array::from_list([1.0, 2.0], [2])).sum() == 3m);
Trait implementations 27
impl<const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::Sqrt for Quantity<f64, { 2 * L }, { 2 * M }, { 2 * T }, { 2 * I }, { 2 * K }, { 2 * N }, { 2 * J }>impl<const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::Pow<i32> for Quantity<f64, L, M, T, I, K, N, J>impl<V: Display, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> Display for Quantity<V, L, M, T, I, K, N, J>impl<V: Debug, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> Debug for Quantity<V, L, M, T, I, K, N, J>impl<V: Clone, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> Clone for Quantity<V, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> Broadcastable<R> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> Materialize<f64, R> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> BroadcastScalar for Quantity<f64, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32, const L2: i32, const M2: i32, const T2: i32, const I2: i32, const K2: i32, const N2: i32, const J2: i32> ops::DotMul<Quantity<Array<f64, R>, L2, M2, T2, I2, K2, N2, J2>> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32, const L2: i32, const M2: i32, const T2: i32, const I2: i32, const K2: i32, const N2: i32, const J2: i32> ops::DotMul<Quantity<f64, L2, M2, T2, I2, K2, N2, J2>> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::DotMul<f64> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::DotMul<Array<f64, R>> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32, const L2: i32, const M2: i32, const T2: i32, const I2: i32, const K2: i32, const N2: i32, const J2: i32> ops::DotDiv<Quantity<Array<f64, R>, L2, M2, T2, I2, K2, N2, J2>> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32, const L2: i32, const M2: i32, const T2: i32, const I2: i32, const K2: i32, const N2: i32, const J2: i32> ops::DotDiv<Quantity<f64, L2, M2, T2, I2, K2, N2, J2>> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::DotDiv<f64> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::DotAdd for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::DotAdd<Quantity<f64, L, M, T, I, K, N, J>> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::DotSub for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::DotSub<Quantity<f64, L, M, T, I, K, N, J>> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::DotLt<Quantity<Array<f64, R>, L, M, T, I, K, N, J>> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::DotLt<Quantity<f64, L, M, T, I, K, N, J>> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::DotGt<Quantity<Array<f64, R>, L, M, T, I, K, N, J>> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::DotGt<Quantity<f64, L, M, T, I, K, N, J>> for Quantity<Array<f64, R>, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32, const L2: i32, const M2: i32, const T2: i32, const I2: i32, const K2: i32, const N2: i32, const J2: i32> ops::DotMul<Quantity<Array<f64, R>, L2, M2, T2, I2, K2, N2, J2>> for Quantity<f64, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32, const L2: i32, const M2: i32, const T2: i32, const I2: i32, const K2: i32, const N2: i32, const J2: i32> ops::DotDiv<Quantity<Array<f64, R>, L2, M2, T2, I2, K2, N2, J2>> for Quantity<f64, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::DotAdd<Quantity<Array<f64, R>, L, M, T, I, K, N, J>> for Quantity<f64, L, M, T, I, K, N, J>impl<const R: usize, const L: i32, const M: i32, const T: i32, const I: i32, const K: i32, const N: i32, const J: i32> ops::DotSub<Quantity<Array<f64, R>, L, M, T, I, K, N, J>> for Quantity<f64, L, M, T, I, K, N, J>
Enums
UnitErrorSource
pub enum UnitErrorWhat went wrong with a unit or a dynamic quantity. A mismatch names both dimensions and the factor that would bridge them; a unit that is not known suggests the closest one.
use units::{Measure, UnitError};
let v = try! Measure::parse("3 m/s");
try v.to_str("s") catch e: UnitError {
println(e); // cannot convert m/s (velocity, L·T⁻¹) to s (time, T): ...
};
Two dimensions that had to agree do not: a conversion, a sum, a comparison.
opsays which.A unit symbol or name that is not in the catalogue.
A unit expression that does not parse.
A number that does not parse, or one that is out of range.
Trait implementations 2
impl Display for UnitErrorimpl Error for UnitError