Units and Error Propagation for Physics in Python

To do math with units and errors (uncertainities), use the Python packages pint (http://pint.readthedocs.org/en/latest/) and uncertainties (http://pythonhosted.org/uncertainties/). While pint has rudimentary support for error proporation, uncertainties is much more robust.

Pint

To use pint, first define a unit registry.


In [ ]:
from pint import UnitRegistry

u = UnitRegistry

Then, define unitted quantities using "dot" syntax on the unit registry. All standard SI units and their prefixes are already defined.


In [3]:
f_c = 50 * u.kHz
k_c = 3 * u.N/u.m
Q = 10000 # or Q = 10000 * u.dimensionless

Then we can calculate, for example, the intrinsic cantilever dissipation.


In [20]:
from numpy import pi

def calc_Gamma_i(f_c, k_c, Q):
        """Calculate the cantilever's intrinsic dissipation."""
        return k_c / (2 * pi * f_c * Q)

Gamma_i = calc_Gamma_i(f_c, k_c, Q)

print Gamma_i
print Gamma_i.ito(u.pN*u.s/u.m)


9.54929658551e-07 newton / kilohertz / meter
954.929658551 piconewton * second / meter
9.54929658551e-07 gram / second

The "ito" method allows us to convert the quantity to the specified units.

Uncertainties

To use uncertainties, import the uncertain float type.


In [21]:
from uncertainties import ufloat

Then, just define quantities using ufloat, and the package will propogate errors.


In [29]:
from uncertainties.umath import sin
print ufloat(3, 0.3) + ufloat(2, 0.5)

print sin(ufloat(0.3, 0.03))


5.0+/-0.6
0.296+/-0.029

Use trigonometric and exponential functions from uncertainties.umath to automatically propogate errors for those functions too.

Using Pint and Uncertainties together

To use them together, just define a ufloat and assign it units. Going back to our original example,


In [30]:
f_cE = ufloat(50000, 0.5) * u.Hz
k_cE = ufloat(3,0.3) * u.N/u.m
QE = ufloat(10000, 200)

Gamma_iE = calc_Gamma_i(f_cE, k_cE, QE)

print Gamma_iE.ito(u.pN*u.s/u.m)


(9.5+/-1.0)e+02 piconewton * second / meter

In [ ]: