TheAlgorithms/Python · error · ValueError

Impossible gravity

Error message

Impossible gravity

What it means

Raised by archimedes_principle when gravity is negative. Unlike density and volume, gravity of exactly 0 is allowed (free-fall / orbit, returns 0.0) — only strictly negative values raise, since negative gravitational acceleration is unphysical in this model. It is the last of the three ordered checks.

Solutions

  1. Pass the magnitude of gravitational acceleration (e.g. 9.8 or 9.81 m/s^2), not a signed vector component
  2. Use gravity=0 deliberately for free-fall/orbital scenarios — it is supported
  3. If your coordinate convention encodes gravity as -9.8, convert with abs()

Example fix

# before
archimedes_principle(fluid_density=997, volume=0.7, gravity=g_vec.y)  # -9.8 -> ValueError

# after
archimedes_principle(fluid_density=997, volume=0.7, gravity=abs(g_vec.y))
Defensive patterns

Strategy: validation

Validate before calling

def valid_gravity(gravity) -> bool:
    return gravity >= 0  # 0 is allowed (free fall); only negative raises

Prevention

When it happens

Trigger: Calling archimedes_principle(gravity=-9.8, ...), e.g. by sign-flipping an acceleration value or using a downward-positive coordinate convention.

Common situations: Physics engines or coordinate systems where the gravity vector is expressed as negative-y, and the signed component is passed instead of its magnitude.

Related errors


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

Appendix: source

Thrown at physics/archimedes_principle_of_buoyant_force.py:54

    ValueError: Impossible object volume
    >>> archimedes_principle(fluid_density=0, volume=0.7)
    Traceback (most recent call last):
        ...
    ValueError: Impossible fluid density
    >>> archimedes_principle(fluid_density=997, volume=0.7, gravity=0)
    0.0
    >>> archimedes_principle(fluid_density=997, volume=0.7, gravity=-9.8)
    Traceback (most recent call last):
        ...
    ValueError: Impossible gravity
    """

    if fluid_density <= 0:
        raise ValueError("Impossible fluid density")
    if volume <= 0:
        raise ValueError("Impossible object volume")
    if gravity < 0:
        raise ValueError("Impossible gravity")

    return fluid_density * gravity * volume


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)