from math import isnan


def clamp(x: float, lower=0., upper=1.) -> float:
    """
    Clamps a float to within a range (default [0, 1]).
    """
    if x <= lower:
        return lower
    elif x >= upper:
        return upper
    elif isnan(x):
        raise FloatingPointError('clamp is undefined for NaN')
    return x