Skip to content

math#

Unit conversions (temperature, frequency, duration, angles) and small numeric helpers.

celsius_to_temperature #

celsius_to_temperature(celsius: float) -> Temperature

Wrap a Celsius number in a unit-aware Temperature value.

clamp #

clamp(
    value: float, min_val: float, max_val: float
) -> float

Restrict a value to [min_val, max_val], clamping to the nearer bound if outside.

convert_duration #

convert_duration(
    value: float,
    from_unit: Literal["ns", "us", "ms", "s", "min", "h"],
    to_unit: Literal["ns", "us", "ms", "s", "min", "h"],
) -> float

Convert a duration between time units (ns, us, ms, s, min, h).

convert_frequency #

convert_frequency(
    value: float,
    from_unit: Literal[
        "hz",
        "Hz",
        "HZ",
        "khz",
        "KHz",
        "KHZ",
        "mhz",
        "MHz",
        "MHZ",
        "ghz",
        "GHz",
        "GHZ",
    ],
    to_unit: Literal[
        "hz",
        "Hz",
        "HZ",
        "khz",
        "KHz",
        "KHZ",
        "mhz",
        "MHz",
        "MHZ",
        "ghz",
        "GHz",
        "GHZ",
    ],
) -> float

Convert a frequency between Hz, kHz, MHz, and GHz (units case-insensitive).

convert_temperature #

convert_temperature(
    value: float,
    from_unit: Literal["C", "K", "F"],
    to_unit: Literal["C", "K", "F"],
) -> float

Convert a temperature between Celsius, Kelvin, and Fahrenheit.

degrees_to_radians #

degrees_to_radians(degrees: float) -> float

Convert an angle from degrees to radians (\(\text{rad} = \deg \times \pi/180\)).

duration_to_nanos #

duration_to_nanos(duration: Duration) -> float

Read a unit-aware Duration back as plain nanoseconds.

frequency_to_hz #

frequency_to_hz(frequency: Frequency) -> float

Read a unit-aware Frequency back as plain hertz.

hz_to_frequency #

hz_to_frequency(hz: float) -> Frequency

Wrap a hertz number in a unit-aware Frequency value.

lerp #

lerp(
    x: float, x1: float, y1: float, x2: float, y2: float
) -> float

Linearly interpolate (or extrapolate) the \(y\) value at x through \((x_1, y_1)\) and \((x_2, y_2)\).

Raises:

Type Description
ValueError

If the two points share an x (x1 == x2).

map_range #

map_range(
    value: float,
    from_min: float,
    from_max: float,
    to_min: float,
    to_max: float,
) -> float

Linearly rescale value from [from_min, from_max] to [to_min, to_max], extrapolating outside.

Raises:

Type Description
ValueError

If the source range is empty (from_min == from_max).

ns_to_duration #

ns_to_duration(ns: int) -> Duration

Wrap a nanosecond count in a unit-aware Duration value.

radians_to_degrees #

radians_to_degrees(radians: float) -> float

Convert an angle from radians to degrees (\(\deg = \text{rad} \times 180/\pi\)).

temperature_to_celsius #

temperature_to_celsius(temperature: Temperature) -> float

Read a Temperature value back as plain degrees Celsius.