TheAlgorithms/Python · error · ValueError

The order must be greater than or equal to 1.

Error message

The order must be greater than or equal to 1.

What it means

Raised by minkowski_distance() in maths/minkowski_distance.py when order < 1. The Minkowski distance of order p is only a valid metric for p >= 1 (p < 1 violates the triangle inequality), so the function rejects such orders before computing sum(abs(a-b)**order) ** (1/order).

Source

Thrown at maths/minkowski_distance.py:34

    >>> minkowski_distance([1.0, 1.0], [2.0, 2.0], 1)
    2.0
    >>> minkowski_distance([1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], 2)
    8.0
    >>> import numpy as np
    >>> bool(np.isclose(5.0, minkowski_distance([5.0], [0.0], 3)))
    True
    >>> minkowski_distance([1.0], [2.0], -1)
    Traceback (most recent call last):
        ...
    ValueError: The order must be greater than or equal to 1.
    >>> minkowski_distance([1.0], [1.0, 2.0], 1)
    Traceback (most recent call last):
        ...
    ValueError: Both points must have the same dimension.
    """
    if order < 1:
        raise ValueError("The order must be greater than or equal to 1.")

    if len(point_a) != len(point_b):
        raise ValueError("Both points must have the same dimension.")

    return sum(abs(a - b) ** order for a, b in zip(point_a, point_b)) ** (1 / order)


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Use p >= 1: p=1 is Manhattan, p=2 is Euclidean.
  2. Constrain hyperparameter search ranges to [1, inf).
  3. If you truly need fractional 'distances', implement them separately rather than bypassing this check.

Example fix

# before
minkowski_distance([1.0, 2.0], [2.0, 3.0], 0.5)

# after
minkowski_distance([1.0, 2.0], [2.0, 3.0], 1.5)
Defensive patterns

Strategy: validation

Validate before calling

if order < 1:
    raise ValueError('Minkowski order must be >= 1')

Prevention

When it happens

Trigger: minkowski_distance([1.0], [2.0], -1), minkowski_distance(a, b, 0), or minkowski_distance(a, b, 0.5) (the fractional 'metric' that is not a true distance).

Common situations: Tuning p as a hyperparameter and sweeping below 1, defaulting p to 0 by mistake, or reading p from config where a typo produces a negative value.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/9252c8771c34d7cf. Report an issue: GitHub.