Ending up with both meters and kilometers using pint in python

232 views Asked by At

Using the pint in code below I somehow end up with both units: meter and kilometer:

107661.59454231549 meter ** 1.5 / kilometer ** 0.5 / second

import math
import pint

u = pint.UnitRegistry()
Q_ = u.Quantity

R_mars = 3396 * u.km
m_mars = 6.419 * 10 ** 23 * u.kg
G = 6.674 * 10 ** (-11) * u.m ** 3 / u.kg / u.s ** 2
R = 300 * u.km + R_mars

def calc_orbital_v(M, R):
    return (G * M / R) ** (1/2)

print(calc_orbital_v(m_mars, R))

Why does pint not automatically convert to a unified unit, either meter or kilometer?

1

There are 1 answers

0
hc_dev On

I didn't find an automatic (implicit), but programmatic (explicit) conversion.

Base Units & Explicit Conversion

You could force conversion to base-units of the configured default system by optionally setting ureg.default_system and using .to_base_units():

import math
import pint

ureg = pint.UnitRegistry()
Q_ = ureg.Quantity

R_mars = 3396 * ureg.km
m_mars = 6.419 * 10 ** 23 * ureg.kg
G = 6.674 * 10 ** (-11) * ureg.m ** 3 / ureg.kg / ureg.s ** 2
R = 300 * ureg.km + R_mars

def calc_orbital_v(M, R):
    return (G * M / R) ** (1/2)

speed = calc_orbital_v(m_mars, R)

print(type(speed))
print(speed)  # before: meters and kilometers mixed
print(ureg.default_system)  # the default unit system can be configured
print(speed.to_base_units())  # after: converted to base-unit meters

Note:

  • for consistency with official pint docs renamed unit-registry to ureg (instead your given u)
  • the unit-system defaults to mks (which will use meters and seconds)

Then resulting output is:

<class 'pint.quantity.build_quantity_class.<locals>.Quantity'>
107661.59454231549 meter ** 1.5 / kilometer ** 0.5 / second
mks
3404.558552792702 meter / second

The concept of default systems and base units seem to exist since version 0.7.