Quantities is a Python library designed to provide support for physical quantities with units, building on the popular NumPy library. It handles arithmetic and conversions of physical quantities, including magnitude, dimensionality, and uncertainty. The current version is 0.16.4. While actively developed with a stable API, test coverage is incomplete, and it is not recommended for mission-critical or production applications. It has an irregular, but active, release cadence.
pip install quantitiesVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates creating quantities with units, performing basic arithmetic, and converting between different units. The recommended practice is to import the library as `pq`.
Use with caution in critical systems; thoroughly test specific use cases or consider more mature alternatives like 'Pint' for production environments.
Ensure that both operands have compatible units. If adding a scalar, it must either be multiplied by a unit or the quantity's magnitude extracted first. Example: `velocity + 3*pq.m/pq.s` or `velocity.magnitude + 3`.
Be aware that temperature quantities represent differences (e.g., a change of 20 degC) rather than absolute points (e.g., 20 degC on the Celsius scale). Calculations involving absolute temperatures might require manual handling or a different library.
For mathematical functions that expect dimensionless inputs (like trigonometric functions), ensure the quantity is dimensionless or extract its magnitude before passing it. For functions where unit-aware behavior is expected, verify the outcome carefully and consider wrapping the function to handle units explicitly.
Upgrade to `quantities` version 0.16.4 or newer to resolve these compatibility issues with NumPy 2.x.
Ensure all operands in an arithmetic expression have compatible units. For example, `velocity + 3 * pq.meter / pq.second` or perform the operation on magnitudes: `velocity.magnitude + 3`.
You cannot modify the definition of a base unit. To change the units of a `Quantity` object, assign a new unit string or `Unit` object to the `units` attribute of the `Quantity` instance, e.g., `q.units = 'feet'` or `q.units = pq.foot` (note the singular form for `pq.foot`).
To get a scalar numerical value from a quantity, use `.magnitude` to access the underlying NumPy array (which might be a 0-d array for scalars) or `.item()` for a Python scalar from a 0-d array. Ensure the quantity is dimensionless if directly converting to a scalar without unit stripping.