Skip to content

units

Unit conversions

unit_converter(value, from_unit, to_unit)

Converts a value from one unit to another

Source code in mmg_toolbox/utils/units.py
def unit_converter(value: float, from_unit: str, to_unit: str):
    """
    Converts a value from one unit to another
    """
    if from_unit in METERS:
        # Distances in meters
        distance = value * METERS[from_unit]
        return distance / METERS[to_unit]
    if from_unit in ENERGY:
        # Energy in eV
        energy = value * ENERGY[from_unit]
        return energy / ENERGY[to_unit]
    if from_unit in ANGLE:
        # Angle in degrees
        angle = value * ANGLE[from_unit]
        return angle / ANGLE[to_unit]
    raise ValueError(f"Unknown unit {from_unit}")