Ethan Herdrick
Ethan Herdrick

Reputation: 303

Python Pint doesn't merge units of the same quantity when multiplying

Using Python Pint, I'm getting a strange result when multiplying units of the same quantity. You would expect them to merge, but they don't. For example:

from pint import UnitRegistry
units = UnitRegistry()

Then:

(3 * units.m) * ( 5 * units.m)  

... results in:

<Quantity(15, 'meter ** 2')>

... which is correct. But if I convert one of the factors to millimeters, like so:

(3 * units.m) * ( 5000 * units.mm)

... it gives a nonsense answer:

<Quantity(15000, 'meter * millimeter')>

The same thing happens with division, and with other dimensions, like mass, time, etc.

However, addition does work:

(3 * units.m) + ( 5000 * units.mm)
<Quantity(8.0, 'meter')>

Anyone know anything about this?

Upvotes: 4

Views: 732

Answers (1)

Santiago Bruno
Santiago Bruno

Reputation: 446

The tutorial mentions to_base_units and to_reduced_units methods, maybe one of them does the conversion you need https://pint.readthedocs.io/en/latest/tutorial.html

It also says that you can instantiate UnitRegistry with parameter auto_reduce_dimensions=True to have this done automatically. It is disabled by default because it may be an expensive operation

Upvotes: 6

Related Questions