TheAlgorithms/Python · error · ValueError

The length should be non-negative

Error message

The length should be non-negative

What it means

Raised by period_of_pendulum(length) in physics/period_of_pendulum.py when length < 0. The small-angle pendulum period T = 2*pi*sqrt(length/g) requires a non-negative pendulum length; length 0 is allowed and returns 0.0. The check runs before the square root, preventing a complex result from a negative radicand.

Source

Thrown at physics/period_of_pendulum.py:46


def period_of_pendulum(length: float) -> float:
    """
    >>> period_of_pendulum(1.23)
    2.2252155506257845
    >>> period_of_pendulum(2.37)
    3.0888278441908574
    >>> period_of_pendulum(5.63)
    4.76073193364765
    >>> period_of_pendulum(-12)
    Traceback (most recent call last):
        ...
    ValueError: The length should be non-negative
    >>> period_of_pendulum(0)
    0.0
    """
    if length < 0:
        raise ValueError("The length should be non-negative")
    return 2 * pi * (length / g) ** 0.5


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Fix the length computation to produce a magnitude: length = abs(bob_y - anchor_y)
  2. Validate inputs at the boundary: reject or clamp length < 0 before calling
  3. In simulations, guard decayed/destroyed pendulum states instead of passing negative lengths

Example fix

# before
period = period_of_pendulum(anchor_y - bob_y)  # negative if bob is above anchor

# after
period = period_of_pendulum(abs(bob_y - anchor_y))
Defensive patterns

Strategy: validation

Validate before calling

if length < 0:
    raise ValueError(f"pendulum length must be >= 0, got {length}")
period = period_of_pendulum(length)

Try / catch

try:
    period = period_of_pendulum(length)
except ValueError:
    length = abs(length)  # only if the sign was a coordinate artifact
    period = period_of_pendulum(length)

Prevention

When it happens

Trigger: period_of_pendulum(-12); any call where the length argument is a negative float, e.g. length = anchor_y - bob_y computed with the operands swapped.

Common situations: Subtraction-order bugs when deriving length from coordinates; feeding signed positions instead of magnitudes; fixtures that use negative numbers to mean 'invalid' without sanitizing them.

Related errors


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