Astropy: Unit Conversion
Documentation
For more information about the features presented below, you can read the astropy.units docs.
Representing units and quantities
Astropy includes a powerful framework for units that allows users to attach units to scalars and arrays, and manipulate/combine these, keeping track of the units.
Since we may want to use a number of units in expressions, it is easiest and most concise to import the units module with:
though note that this will conflict with any variable called u.
Units can then be accessed with:
We can create composite units:
The most useful feature about the units is the ability to attach them to scalars or arrays, creating Quantity objects:
Combining and converting units
Quantities can then be combined:
and converted to different units:
The units and value of a quantity can be accessed separately via the value and unit attributes:
Advanced features
The units of a quantity can be decomposed into a set of base units using the decompose() method. By default, units will be decomposed to S.I.:
To decompose into c.g.s. units, one can do:
Using physical constants
The astropy.constants module contains physical constants relevant for Astronomy, and these are defined with units attached to them using the astropy.units framework.
If we want to compute the Gravitational force felt by a 100. * u.kg space probe by the Sun, at a distance of 3.2au, we can do:
The full list of available physical constants is shown here (and additions are welcome!).
Equivalencies
Equivalencies can be used to convert quantities that are not strictly the same physical type:
Integration with Numpy Functions
Some of the Numpy functions understand Quantity objects:
Practical Exercises
Level 1
What is 1 barn megaparsecs in teaspoons? Note that teaspoons are not part of the standard set of units, but it can be found in:
Level 2
What is 3 nm^2 Mpc / m^3 in dimensionless units?