Base Dimensions and Units

SI prefixes

SI Prefix

Short Prefix

Order of Magnitude

yotta

Y

1024

zetta

Z

1021

exa

E

1018

peta

P

1015

tera

T

1012

giga

G

109

mega

M

106

kilo

k

103

hecto

h

102

deka

da

101

deci

d

10-1

centi

c

10-2

milli

m

10-3

micro

μ

10-6

nano

n

10-9

pico

p

10-12

femto

f

10-15

atto

a

10-18

zepto

z

10-21

yocto

y

10-24

Each of the SI base units also have versions with these prefixes applied. Here, those are meters for length, seconds for time, grams for mass (kilograms are the consistent base unit but the prefixes are applied to grams), kelvin for temperature, moles for quantity, and amperes for current.

Length

The full suite of functions on a unit is shown for meters here as an example. All units have exactly the same interface so the copies are omitted for brevity.

class pyunitx.length.meters(value: Decimal | float | str)

Meters are the base SI unit of length. It is currently defined in terms of the speed of light.

__abs__()

Get the absolute value of this measurement.

Returns:

A copy of this measurement as an absolute value.

__add__(other: UnitBase | int | float | Decimal) UnitBase

Add two measurements of the same unit together.

Parameters:

other – Another measurement, with the same units.

Raises:

TypeError – If measurements are not the same unit.

Returns:

A measurement with the values of the two added.

__eq__(other)

Check if this measurement is the same value and unit of another.

Parameters:

other – Another measurement, with the same units.

Returns:

Whether these two measurements are identical.

__format__(format_spec)

Format this measurement similar to a float.

Parameters:

format_spec – The format specification, in a restricted subset of the python string formatting mini-language. Currently only supports .[precision]g to round to the specified number of significant figures.

__getattr__(key: str)

Forward conversion requests to the dimension.

The dimension, being the one thing all compatible units have in common, is the logical place to store all conversion functions between different units.

Any x.to_* method calls are therefore passed to the dimension.

Parameters:

key – The method name.

Returns:

A pseudo-bound method of the conversion function.

Raises:

AttributeError – If the requested method doesn’t look like a conversion function, or if there isn’t a conversion function by that name.

__le__(other)

Check if this measurement is less than or equal to another.

Parameters:

other – The measurement to compare to.

Raises:

TypeError – If the two arguments are different units and can therefore not be compared.

Returns:

Whether the other measurement is less than this one.

__lt__(other)

Check if this measurement is less than another.

Parameters:

other – The measurement to compare to.

Raises:

TypeError – If the two arguments are different units and can therefore not be compared.

Returns:

Whether the other measurement is less than this one.

__mul__(other: UnitBase | int | float | Decimal) UnitBase | Decimal

Multiply two measurements.

If the two quantities completely cancel (like a frequency times a duration), the result will be returned as a plain number.

Otherwise, produce the correct unit by combining the units of the two multiplicands. If the result has two base units that measure the same dimension but are not the same (say you’re trying to multiply ft/s by m^2, ft*m^2 would be in the result) a TypeError will be thrown. Instead you should convert one of the measurements to be compatible with the other before multiplying. In the example, that could be converting the ft/s to m/s.

Parameters:

other – Another measurement, with any units including none.

Raises:

TypeError – If base units are incompatible.

Returns:

The result of the calculation, with the compound units.

__neg__()

Get the negative of this measurement.

Returns:

A copy of this measurement with sign flipped.

static __new__(cls, value: Decimal | float | str)

Create a new measurement using this unit.

Instances are flyweights; two invocations of meters(1) will return the same object.

Parameters:

value – The numerical value of the measurement, in any form that decimal.Decimal can accept.

Returns:

The newly created measurement, or the cached version.

__pos__()

No-op, return self.

This is unlike any other math operation since it doesn’t make a copy.

__pow__(other: int | float | Decimal | Fraction | str)

Raise this measurement to a power.

For instance, meters(4) ** 2 == meters_squared(16). You can also compute the magnitude of a vector with vec = [meters(4), meters(3)]; mag = (vec[0] ** 2 + vec[1] ** 2) ** (1/2).

While the power of 1/2 (square root) can be exactly represented as a float, in general fractional powers will not be. For these cases you can use fractions.Fraction.

Anything other than fractions will be run through the decimal.Decimal constructor first, so you can use anything including strings to represent the number.

Parameters:

other – Any integer, the power to raise this measurement to.

Returns:

A measurement with the value and units raised to the power.

__sub__(other: UnitBase | int | float | Decimal) UnitBase

Subtract a measurement of the same unit from this.

Parameters:

other – Another measurement, with the same units.

Raises:

TypeError – If measurements are not the same unit.

Returns:

A measurement with the values of the two subtracted.

__truediv__(other: UnitBase | int | float | Decimal) UnitBase | Decimal

Divide two measurements.

If the two quantities completely cancel (like the derivation of radians dividing length by length), the result will be returned as a plain number.

Otherwise, produce the correct unit by combining the units of the two divisors. If the result has two base units that measure the same dimension but are not the same (say you’re trying to divide ft/s by m^2, ft/m^2 would be in the result) a TypeError will be thrown. Instead you should convert one of the measurements to be compatible with the other before multiplying. In the example, that could be converting the ft/s to m/s.

Parameters:

other – Another measurement, with any units including none.

Raises:

TypeError – If base units are incompatible.

Returns:

The result of the division, with correct units.

equivalent_to(other: UnitBase, figs=5) bool

Check if this measurement represents the same quantity as another, within a certain precision.

This effectively converts both units to the base unit to get them on equal footing before rounding and checking equality.

Parameters:
  • other – The other measurement.

  • figs – How many significant figures to round to before comparison.

Raises:

TypeError – If the two units do not represent the same dimension and therefore cannot be compared.

Returns:

Whether the two measurements are approximately equal.

is_dimension(dim: DimensionBase) bool

Check if this unit is of the given dimension.

Most useful for checking whether two measurements can be reasonably compared with .equivalent_to or converted into the other.

Parameters:

dim – The dimension to check against.

Returns:

Whether this unit is of the given dimension.

sig_figs(figs=3)

Produce a version of this measurement rounded to significant figures.

Parameters:

figs – How many significant figures to round to.

Returns:

A new measurement with a rounded value.

to_latex(siunitx_major_version=3)

Output this unit value as it would be used in LaTeX with siunitx.

Maybe script your calculations, then write the output to a .tex file and include it in your main document.

Parameters:

siunitx_major_version – siunitx changed the name of its macro that outputs a number with a unit in version 3.0. Prior, it was \SI{number}{units}, and after it was \qty{number}{units}. Defaults to the most recent version. If you’re using an older one, for instance if your TeXLive distribution is a few years old, pass in pyunitx.SIUNITX_OLD, an alias for 2. I doubt anyone is using version 1.

Returns:

A string formatted for direct inclusion in LaTeX.

to_natural_si()

Convert this value to the most natural SI prefix.

For instance, a value of 12100 meters would be changed into 12.1 kilometers. This only works on units that have a specific name. Elementary units like meters of course work, as do composite units like joules. However, if a unit can only be expressed by some combination of named units (say N*s) then a TypeError will be raised.

Currently ignores 10^-2 through 10^2; that is, centi through hecto. These are not used nearly as often, with the exception of the centimeter.

Raises:
  • TypeError – If this unit is not an SI unit.

  • ValueError – If the value of this unit is too big or too small to be directly expressed with an SI prefix. Instead you should probably express your value as scientific notation using the base unit of the dimension.

Returns:

This value expressed in the unit that requires no extra scientific notation.

pyunitx.length.astronomical_unit

alias of au

class pyunitx.length.au(value: Decimal | float | str)

One astronomical unit, or AU, is the average distance between Earth and the Sun. It’s used in astronomical measurements, and is part of the definition of the parsecs.

class pyunitx.length.feet(value: Decimal | float | str)

Feet are the base unit of length in the US Customary System.

class pyunitx.length.inches(value: Decimal | float | str)

Twelve inches make up one foot.

class pyunitx.length.miles(value: Decimal | float | str)

Miles are the long distance measure in the US Customary System.

class pyunitx.length.yards(value: Decimal | float | str)

One yard is equal to three feet.

Time

Defines common units of time.

For better handling of dates and times, use datetime from the standard library. This module is suitable for manipulation of time intervals and rates that show up in other calculations but knows absolutely nothing about leap seconds or even dates.

class pyunitx.time.days(value: Decimal | float | str)

A solar day is exactly 24 hours. The solar day is loosely defined as the period between zeniths of the sun.

class pyunitx.time.hours(value: Decimal | float | str)

One hour is sixty minutes.

class pyunitx.time.julian_years(value: Decimal | float | str)

It’s nice to have a definition of a year that doesn’t vary with things like leap years, and the Julian year is that.

class pyunitx.time.minutes(value: Decimal | float | str)

One minute is sixty seconds.

class pyunitx.time.seconds(value: Decimal | float | str)

The second is the SI base unit of time. As there are convenient larger units for time already, the positive SI prefixes (k, M, G) aren’t used very much but the negative ones (m, μ, n) do see common use.

class pyunitx.time.sidereal_days(value: Decimal | float | str)

While the earth is spinning, it is also orbiting the sun. The movement along the orbit over the course of the day means that the sun has moved backwards a bit so the earth has to do some extra rotation before the sun is in the same place again. If you instead hovered above one of the poles with a fixed orientation, and tracked the time it took for the earth to rotate back into the same position, you would get the length of the sidereal day. This is a little shorter than a solar day.

class pyunitx.time.years(value: Decimal | float | str)

This is the most common, solar definition of the year—the time it takes for the earth to complete one orbit around the sun. Somewhat more precisely it is the interval between subsequent vernal equinoxes (or summer solstices, they’re all identical).

Mass

class pyunitx.mass.atomic_mass_unit(value: Decimal | float | str)

The unified atomic mass unit is defined as 1/12 of the mass of one atom of carbon-12, approximately the mass of one proton or neutron. As such, it is equal to \frac{1 g}{N_A}.

class pyunitx.mass.grams(value: Decimal | float | str)

A gram is roughly defined as the mass of a milliliter of water.

class pyunitx.mass.kilograms(value: Decimal | float | str)

Kilograms are the SI base unit of mass, despite having a magnitude prefix.

class pyunitx.mass.pounds_mass(value: Decimal | float | str)

Avoirdupois pounds are one of the definitions of mass in the US Customary System.

class pyunitx.mass.slugs(value: Decimal | float | str)

A slug is the amount of mass that would be accelerated at 1 foot/second/second by a force of one pound. Using slugs you can form a consistent set of measurements whereas the pound-mass cannot.

class pyunitx.mass.tonnes(value: Decimal | float | str)

A metric tonne is equal to 1000 kilograms. This is equivalent to a megagram (Mg) and is easily confusable with the short ton, so the megagram should be preferred.

class pyunitx.mass.tons(value: Decimal | float | str)

One short ton is 2000 pounds. It should not be confused with the metric tonne, which is 1000 kilograms.

pyunitx.mass.troy_pound

alias of troy_pounds_mass

Temperature

Conversions between these units are deltas, as the systems have different zeros.

class pyunitx.temperature.celsius(value: Decimal | float | str)

Within this module, all temperatures are treated as deltas, ignoring the fact that the systems have different zeros. Thus, calling celsius(25).to_kelvin() will not produce kelvin(298.15) as you might expect, but rather kelvin(25). To help out, the value of absolute zero has been provided in each of the non-absolute units.

To convert from a direct measurement in degrees Celsius to one in Kelvin, use (<celsius measurement> - absolute_zero_celsius).to_kelvin(). The to_kelvin at the end is of course not strictly necessary, depending on how you are interpreting the results, but is certainly in line with intention.

class pyunitx.temperature.fahrenheit(value: Decimal | float | str)

Within this module, all temperatures are treated as deltas, ignoring the fact that the systems have different zeros. Thus, calling fahrenheit(25).to_rankine() will not produce rankine(484.67) as you might expect, but rather rankine(25). To help out, the value of absolute zero has been provided in each of the non-absolute units.

To convert from a direct measurement in degrees Fahrenheit to one in degrees Rankine, use (<fahrenheit measurement> - absolute_zero_fahrenheit).to_rankine(). The to_rankine at the end is of course not strictly necessary, depending on how you are interpreting the results, but is certainly in line with intention.

class pyunitx.temperature.kelvin(value: Decimal | float | str)

Within this module, all temperatures are treated as deltas, ignoring the fact that the systems have different zeros. Thus, calling celsius(25).to_kelvin() will not produce kelvin(298.15) as you might expect, but rather kelvin(25). To help out, the value of absolute zero has been provided in each of the non-absolute units.

Kelvin is the absolute measure of temperature in the SI system. Its units are equal in size to the Celsius degree, but its zero point is at absolute zero.

class pyunitx.temperature.rankine(value: Decimal | float | str)

Within this module, all temperatures are treated as deltas, ignoring the fact that the systems have different zeros. Thus, calling fahrenheit(25).to_rankine() will not produce rankine(484.67) as you might expect, but rather rankine(25). To help out, the value of absolute zero has been provided in each of the non-absolute units.

Degrees Rankine are the US Customary scale’s absolute temperature scale. Its degrees are the same size as Fahrenheit but its zero is at absolute zero.

Angle

class pyunitx.angle.arcminutes(value: Decimal | float | str)

An arcminute is 1/60 of a degree.

class pyunitx.angle.arcseconds(value: Decimal | float | str)

An arcsecond is 1/60 of an arcminute, and therefore 1/3600 of a degree.

class pyunitx.angle.degrees(value: Decimal | float | str)

Degrees are a measure of angles. 360 degrees extend around a circle. The true base unit of angle is the dimensionless radian, but degrees see common use as well.

All angle measurements in this module are equipped with a to_radians method alongside the other conversion functions that work between the angle measurements defined here. Note that radians are dimensionless so this will return a plain number. To convert from radians to degrees, use degrees.from_radians().

static from_dms(d, m=None, s=None)

Convert from degrees/minutes/seconds notation into a degrees measurement.

Parameters:
  • d – If this is called with three numbers, a number of degrees. If this is called with a single sequence of three numbers, a number of degrees. If this is called with a string, that string should either be a number of decimal degrees (e.g. “-1.23°”) or be in DMS notation (e.g. “1°30′36.36″”). The minute symbol accepts the proper prime ′ or it can be the apostrophe ‘. Similarly the second symbol accepts either double prime ″ or quote “. If DMS is given, decimal seconds are allowed but the degrees and minutes must be whole numbers.

  • m – A number of arcminutes, optional.

  • s – A number of arcseconds, optional.

Returns:

A measurement in degrees.

static from_radians(rad)

Convert a radian value into degrees.

Parameters:

rad – The radian value, as a number.

Returns:

The degree equivalent.

Moles

class pyunitx.mole.moles(value: Decimal | float | str)

A mole is the number of atoms in 12 grams of carbon-12.

It basically is a dimensionless quantity, but is included in the SI system for its pragmatic usefulness in chemistry and fluid physics.

class pyunitx.mole.pound_moles(value: Decimal | float | str)

One lbmol is equal to the number of atoms in 12 lbm of carbon-12. As such it is as much larger than the mol as a lbm is larger than a gram.

Current

class pyunitx.current.amperes(value: Decimal | float | str)

An ampere is a rate of charge movement equal to one coulomb per second. It is one of the fundamental units in the SI system.

Data

class pyunitx.data.bits(value: Decimal | float | str)

A bit is the smallest possible unit of data, representing the state of a system that has exactly two possible states.

class pyunitx.data.bytes(value: Decimal | float | str)

The modern definition of a byte is 8 bits. Originally, this just meant “the smallest addressable unit of memory” and could vary between different computers.

class pyunitx.data.exbibytes(value: Decimal | float | str)

One EiB is 10246 bytes.

Use of the SI prefixes kilo, etc. are discouraged with data as the most natural set of scales are based on powers of two. Thus prefixes are selected using 210 = 1024, which is close to 1000.

class pyunitx.data.gibibytes(value: Decimal | float | str)

One GiB is 10243 bytes.

Use of the SI prefixes kilo, etc. are discouraged with data as the most natural set of scales are based on powers of two. Thus prefixes are selected using 210 = 1024, which is close to 1000.

class pyunitx.data.kibibytes(value: Decimal | float | str)

One KiB is 1024 bytes.

Use of the SI prefixes kilo, etc. are discouraged with data as the most natural set of scales are based on powers of two. Thus prefixes are selected using 210 = 1024, which is close to 1000.

class pyunitx.data.mebibytes(value: Decimal | float | str)

One MiB is 10242 bytes.

Use of the SI prefixes kilo, etc. are discouraged with data as the most natural set of scales are based on powers of two. Thus prefixes are selected using 210 = 1024, which is close to 1000.

class pyunitx.data.nybbles(value: Decimal | float | str)

One nybble is half a byte, 4 bits. It is generally not used for bulk data, only really for low-level work where every bit counts. Some CPU architectures allow nybble-level manipulations.

class pyunitx.data.tebibytes(value: Decimal | float | str)

One TiB is 10244 bytes.

Use of the SI prefixes kilo, etc. are discouraged with data as the most natural set of scales are based on powers of two. Thus prefixes are selected using 210, which is close to 1000.