杰瑞科技汇

Python quantities如何进行单位转换?

Of course! The term "quantities" in Python can refer to two main things:

Python quantities如何进行单位转换?-图1
(图片来源网络,侵删)
  1. The quantities library: A popular third-party library for handling physical quantities (like 5 meters, 10 kg/s, etc.), which includes units and dimensions.
  2. General programming with "quantities": The concept of representing and manipulating any kind of quantity in your code, which is a fundamental part of programming.

Let's break down both.


The quantities Library (Physical Quantities)

This is the most direct answer to your query. The quantities library is built on top of NumPy and allows you to perform calculations with physical units, automatically handling unit conversions and dimensional analysis.

Key Features:

  • Units: Attach units to numerical values (e.g., 5 * m).
  • Dimensional Analysis: Automatically checks for dimensional consistency in calculations. For example, you can't add a length to a mass.
  • Automatic Conversion: Results are often returned in a standard unit, but you can easily convert them.
  • NumPy-like Operations: It works seamlessly with NumPy arrays and functions.

Installation:

First, you need to install it. It's often installed alongside numpy and uncertainties.

pip install quantities numpy

Basic Usage:

import quantities as q
# --- Defining Quantities ---
# You can use common abbreviations or full unit names
length = 10 * q.meter
speed = 5 * q.meter / q.second
time = 2 * q.second
mass = 70 * q.kilogram
print(f"Length: {length}")
print(f"Speed: {speed}")
print(f"Time: {time}")
print(f"Mass: {mass}")
# --- Arithmetic Operations ---
# Operations automatically handle units
distance = speed * time
print(f"\nDistance traveled: {distance}")
# You can add quantities with the same unit
total_length = length + 5 * q.meter
print(f"Total length: {total_length}")
# --- Dimensional Analysis ---
# This will raise an error because you can't add length and time
try:
    invalid_sum = length + time
except Exception as e:
    print(f"\nError as expected: {e}")
# --- Unit Conversion ---
# Convert a result to a different unit
distance_in_km = distance.rescale('km')
print(f"Distance in kilometers: {distance_in_km}")
# You can also convert to compound units
speed_in_mph = speed.rescale('mile/hour')
print(f"Speed in miles per hour: {speed_in_mph:.2f}")
# --- Working with NumPy ---
import numpy as np
# Create an array of quantities
temp_data = np.array([20, 22, 25, 19]) * q.degC
# Apply numpy functions
mean_temp = np.mean(temp_data)
print(f"\nMean temperature: {mean_temp}")
# Note: Quantities library has some limitations with very recent NumPy versions.
# For more advanced and actively maintained unit support, see the `pint` library below.

General Programming with "Quantities"

Beyond the specific library, representing "quantities" is a common task. Here are the standard Pythonic ways to do it, from simple to more robust.

Python quantities如何进行单位转换?-图2
(图片来源网络,侵删)

Method 1: Using Tuples (Simple and Direct)

A tuple (value, unit) is a lightweight and easy way to represent a quantity.

# Define a quantity
speed = (25.5, 'm/s')
# Access value and unit
value = speed[0]
unit = speed[1]
print(f"Value: {value}, Unit: {unit}")
# Function to add two quantities with the same unit
def add_tuples(q1, q2):
    if q1[1] != q2[1]:
        raise ValueError("Units must be the same to add.")
    return (q1[0] + q2[0], q1[1])
total_speed = add_tuples(speed, (10.0, 'm/s'))
print(f"Total speed: {total_speed}")

Pros: Simple, no external libraries needed. Cons: No automatic unit handling, error-prone, requires manual functions for every operation.

Method 2: Using Dictionaries (More Readable)

A dictionary with keys like 'value' and 'unit' is more descriptive than a tuple.

# Define a quantity
pressure = {'value': 101.3, 'unit': 'kPa'}
# Access values
print(f"Pressure is {pressure['value']} {pressure['unit']}")
# You can create a simple class to make it easier to work with
class Quantity:
    def __init__(self, value, unit):
        self.value = value
        self.unit = unit
    def __repr__(self):
        return f"Quantity(value={self.value}, unit='{self.unit}')"
    def __add__(self, other):
        if self.unit != other.unit:
            raise ValueError("Units must be the same to add.")
        return Quantity(self.value + other.value, self.unit)
# Using the class
q1 = Quantity(10, 'kg')
q2 = Quantity(5, 'kg')
q3 = q1 + q2
print(f"\nSum: {q3}")

Pros: More readable and structured than a tuple. The class approach is more extensible. Cons: Still requires manual implementation of logic (like conversion, etc.).

Python quantities如何进行单位转换?-图3
(图片来源网络,侵删)

Method 3: Using Dataclasses (Modern & Recommended)

For Python 3.7+, dataclasses provide a clean, concise way to create classes like the one above.

from dataclasses import dataclass
@dataclass
class Quantity:
    value: float
    unit: str
    def __add__(self, other):
        if self.unit != other.unit:
            raise ValueError("Units must be the same to add.")
        return Quantity(self.value + other.value, self.unit)
# Usage is identical to the class above
q1 = Quantity(10, 'kg')
q2 = Quantity(5, 'kg')
q3 = q1 + q2
print(f"Sum: {q3}")

Pros: Very clean syntax, less boilerplate code than a standard class. The standard library way to do this. Cons: Still requires manual implementation of logic.


Alternative: The pint Library

While quantities is good, the pint library is arguably more popular, powerful, and actively maintained. It's often considered the modern standard for physical units in Python.

Installation:

pip install pint

Basic pint Usage:

import pint
# Create a "UnitRegistry" - this is the core of pint
ureg = pint.UnitRegistry()
# Define quantities using the registry
length = 10 * ureg.meter
speed = 5 * ureg.meter / ureg.second
time = 2 * ureg.second
print(f"Length: {length}")
print(f"Speed: {speed}")
# --- Calculations ---
distance = speed * time
print(f"Distance: {distance}")
# --- Unit Conversion ---
# The syntax is very intuitive
distance_in_km = distance.to('kilometer')
print(f"Distance in km: {distance_in_km}")
# --- Dimensional Analysis ---
# Adding length and time raises an error
try:
    invalid_sum = length + time
except pint.DimensionalityError as e:
    print(f"\nPint Error: {e}")
# --- Powerful Features ---
# You can even define your own units
ureg.define('new_unit = 2 * meter')
my_length = 5 * ureg.new_unit
print(f"My custom length: {my_length}")
print(f"My length in meters: {my_length.to('meter')}")

Summary and Recommendation

Method Best For Pros Cons
quantities library Quick calculations with units. Good NumPy integration, easy to start. Less active development than pint.
pint library Recommended for serious scientific/engineering work. Extremely powerful, active, intuitive syntax, great documentation. Slightly more setup (creating the registry).
Tuples / Dictionaries Simple scripts or when you can't use external libraries. No dependencies, simple. Manual, error-prone, no automatic logic.
Dataclasses Creating a robust, structured quantity type yourself. Clean, Pythonic, extensible. Requires you to write all the logic.

Recommendation:

  • For any serious project involving physical units, use the pint library. It is the industry standard for a reason.
  • If you just need to do a few quick calculations and pint is not an option, the quantities library is a fine alternative.
  • If you cannot use any third-party libraries and need a simple representation, a dataclass is the most robust and "Pythonic" way to build it yourself.
分享:
扫描分享到社交APP
上一篇
下一篇