TheAlgorithms/Python · error · ValueError

Distance cannot be negative

Error message

Distance cannot be negative

What it means

Thrown by couloumbs_law() when distance < 0 while exactly one argument is 0. Distance in Coulomb's law is a separation magnitude (r^2 in the formula), so negative values are non-physical; only zero is tolerated — and only as the 'unknown' marker solved by sqrt(k*q1*q2/|F|).

Source

Thrown at electronics/coulombs_law.py:66

    >>> couloumbs_law(force=0, charge1=0, charge2=5, distance=2000)
    Traceback (most recent call last):
      ...
    ValueError: One and only one argument must be 0

    >>> couloumbs_law(force=0, charge1=3, charge2=5, distance=-2000)
    Traceback (most recent call last):
      ...
    ValueError: Distance cannot be negative

    """

    charge_product = abs(charge1 * charge2)

    if (force, charge1, charge2, distance).count(0) != 1:
        raise ValueError("One and only one argument must be 0")
    if distance < 0:
        raise ValueError("Distance cannot be negative")
    if force == 0:
        force = COULOMBS_CONSTANT * charge_product / (distance**2)
        return {"force": force}
    elif charge1 == 0:
        charge1 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge2)
        return {"charge1": charge1}
    elif charge2 == 0:
        charge2 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge1)
        return {"charge2": charge2}
    elif distance == 0:
        distance = (COULOMBS_CONSTANT * charge_product / abs(force)) ** 0.5
        return {"distance": distance}
    raise ValueError("Exactly one argument must be 0")


if __name__ == "__main__":
    import doctest

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass the magnitude of the separation: abs(x2 - x1).
  2. Compute distance with math.dist / hypot which are always non-negative.
  3. Reserve 0 exclusively for the argument you want solved.

Example fix

# before
couloumbs_law(force=0, charge1=3, charge2=5, distance=x1 - x2)  # can be negative

# after
couloumbs_law(force=0, charge1=3, charge2=5, distance=abs(x1 - x2))
Defensive patterns

Strategy: validation

Validate before calling

from math import dist
r = dist(p1, p2)  # always non-negative
if r < 0:
    raise AssertionError("unreachable")
result = couloumbs_law(force=0, charge1=3, charge2=5, distance=r)

Prevention

When it happens

Trigger: couloumbs_law(force=0, charge1=3, charge2=5, distance=-2000) — exactly one zero but a negative distance.

Common situations: Signed displacement vectors fed into a scalar law; coordinate differences computed as x1-x2 without abs(); physics engine integration reusing signed positions.

Related errors


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