TheAlgorithms/Python · error · ValueError

Distance can not be negative

Error message

Distance can not be negative

What it means

Raised by gravitational_law() when distance is negative. Separation between two masses is a non-negative scalar in the inverse-square law, so negative distances are rejected after the zero-count and force checks. It fires whether distance is the known value or would be used in a computation.

Source

Thrown at physics/newtons_law_of_gravitation.py:77

    >>> gravitational_law(force=36337.283, mass_1=-674, mass_2=0, distance=35584)
    Traceback (most recent call last):
        ...
    ValueError: Mass can not be negative

    >>> gravitational_law(force=-847938e12, mass_1=674, mass_2=0, distance=9374)
    Traceback (most recent call last):
        ...
    ValueError: Gravitational force can not be negative
    """

    product_of_mass = mass_1 * mass_2

    if (force, mass_1, mass_2, distance).count(0) != 1:
        raise ValueError("One and only one argument must be 0")
    if force < 0:
        raise ValueError("Gravitational force can not be negative")
    if distance < 0:
        raise ValueError("Distance can not be negative")
    if mass_1 < 0 or mass_2 < 0:
        raise ValueError("Mass can not be negative")
    if force == 0:
        force = GRAVITATIONAL_CONSTANT * product_of_mass / (distance**2)
        return {"force": force}
    elif mass_1 == 0:
        mass_1 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_2)
        return {"mass_1": mass_1}
    elif mass_2 == 0:
        mass_2 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_1)
        return {"mass_2": mass_2}
    elif distance == 0:
        distance = (GRAVITATIONAL_CONSTANT * product_of_mass / (force)) ** 0.5
        return {"distance": distance}
    raise ValueError("One and only one argument must be 0")


# Run doctest

View on GitHub (pinned to f5988cc097)

Solutions

  1. Compute distance as a magnitude, e.g. distance = abs(p2 - p1) or math.dist(pos1, pos2)
  2. Fix argument order in the subtraction producing the distance
  3. Validate distance >= 0 at the data source before feeding the solver

Example fix

# before
distance = body2_x - body1_x  # can be negative
gravitational_law(force=1e12, mass_1=674, mass_2=0, distance=distance)

# after
distance = abs(body2_x - body1_x)
gravitational_law(force=1e12, mass_1=674, mass_2=0, distance=distance)
Defensive patterns

Strategy: validation

Validate before calling

import math
distance = math.dist(position_1, position_2)  # always >= 0
assert distance >= 0

Try / catch

try:
    gravitational_law(force, m1, m2, distance)
except ValueError as e:
    if "Distance" in str(e):
        raise ValueError(f"bad separation: {distance}") from e
    raise

Prevention

When it happens

Trigger: gravitational_law(force=847938e12, mass_1=674, mass_2=0, distance=-9374); any call where the fourth argument is less than 0, e.g. distance computed as (a - b) that underflowed to a negative number.

Common situations: Coordinate-frame mistakes where a relative position along one axis is used as a distance; subtraction that produced a negative value due to argument order (distance = p1 - p2 instead of abs(p1 - p2)); unit tests with arbitrary sign-filled fixtures.

Related errors


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