2

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?

hc_dev
  • 8,389
  • 1
  • 26
  • 38
Ludwiggle
  • 23
  • 3
  • Why should it (or how should it guess it)? You are feeding it meters and kilometers, how should it know which to convert? You can of course convert the answer by adding .to('weasels ** 1.5/furlong ** 0.5/fortnite') – andy Jul 20 '21 at 15:59

1 Answers1

0

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.

hc_dev
  • 8,389
  • 1
  • 26
  • 38