Date

This semester I began using the Pint library while writing solutions for the problem sets in my classes. I love using this library. It now feels dangerous to me to perform calculations without the computer keeping track of the units. The ability to define arbitrary units is also useful for calculations that don't have physical quantities.

Some of my students became comfortable with the library and are able now to use it independently. While it is important that students be able to manually convert between units, it is also important to teach them that automated ways to convert them exist.

# Basic Usage¶

You start by importing the library and creating an object that holds the information about units.

In [1]:
from pint import UnitRegistry
u = UnitRegistry()


Once you have this dictionary-like object, you can use it to define units and multiply them by values to get physical quantities. When you do further operations, the units are also computed.

In [2]:
length = 10 * u.meter
width = 5 * u.meter
length * width

Out[2]:
50 meter2

One way excellent feature is the ability to convert units by using the to method.

In [3]:
(length * width).to(u.feet**2)

Out[3]:
538.1955208354861 foot2

This allows you to mix units and then convert at the end of the calculation.

In [4]:
length = 10 * u.meter
width = 15 * u.feet
print('unconverted:', length * width)
print('converted:', (length*width).to(u.feet**2))

unconverted: 150 foot * meter
converted: 492.12598425196836 foot ** 2


Some conversions that your discipline might consider automatic may need explicit help.

In [5]:
voltage = 120 * u.volt
current = 12.5 * u.amp
print('unconverted:', voltage * current)
print('converted:', (voltage * current).to(u.watt))

unconverted: 1500.0 ampere * volt
converted: 1500.0 watt


# Arbitrary Units and Prefixes¶

Not all units that we may want to keep track of are fundamental physical units.

In [6]:
u.define('people = []')
u.define('pizza = []')

party_goers = 24 * u.people
appetite = 0.25 * u.pizza / u.people

party_goers * appetite

Out[6]:
6.0 pizza

Energy has many arcane units that can be easily defined and manipulated.

In [7]:
u.define('BOE = 5.4e9 joule')
(1 * u.BOE / u.year).to(u.watt)

Out[7]:
171.11932906041986 watt
In [8]:
u.define('hella- = 1e27')
(1 * u.hellameter).to(u.lightyear)

Out[8]:
105700083402.46153 light_year

There are also some utilities for formatting that are useful.

In [9]:
'{:.2e}'.format((1 * u.lightyear).to(u.meter))

Out[9]:
'9.46e+15 meter'

# Future Work¶

Students frequently perform calculations where it is important to distinguish between a kilogram of coal and a kilogram of carbon dioxide. It would be nice to be able to attach this information to a calculation. I haven't come up with a satisfactory way to do this yet.