TheAlgorithms/Python · error · ValueError

Speed must not exceed light speed 299,792,458 [m/s]!

Error message

Speed must not exceed light speed 299,792,458 [m/s]!

What it means

Raised by beta(velocity) in lorentz_transformation_four_vector when velocity exceeds c = 299,792,458 m/s. beta computes v/c for the Lorentz transformation, and superluminal speeds make the Lorentz factor imaginary, so they are rejected outright. Inputs are assumed to be in m/s.

Source

Thrown at physics/lorentz_transformation_four_vector.py:56


# Vehicle's speed divided by speed of light (no units)
def beta(velocity: float) -> float:
    """
    Calculates β = v/c, the given velocity as a fraction of c
    >>> beta(c)
    1.0
    >>> beta(199792458)
    0.666435904801848
    >>> beta(1e5)
    0.00033356409519815205
    >>> beta(0.2)
    Traceback (most recent call last):
      ...
    ValueError: Speed must be greater than or equal to 1!
    """
    if velocity > c:
        raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!")
    elif velocity < 1:
        # Usually the speed should be much higher than 1 (c order of magnitude)
        raise ValueError("Speed must be greater than or equal to 1!")

    return velocity / c


def gamma(velocity: float) -> float:
    """
    Calculate the Lorentz factor y = 1 / √(1 - v²/c²) for a given velocity
    >>> gamma(4)
    1.0000000000000002
    >>> gamma(1e5)
    1.0000000556325075
    >>> gamma(3e7)
    1.005044845777813
    >>> gamma(2.8e8)
    2.7985595722318277

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass velocity in m/s and clamp to at most c: min(v, 299792458.0) when computing limits.
  2. Fix unit conversion (km/s -> m/s means multiply by 1000, so 0.9c is 269813212.2 m/s).
  3. Catch ValueError and reject FTL inputs at your API boundary.

Example fix

# before
beta(3e8)  # ValueError: exceeds c

# after
C = 299_792_458.0
beta(min(3e8, C))  # clamped, beta(c) == 1.0
Defensive patterns

Strategy: validation

Validate before calling

C = 299_792_458.0  # m/s
if not (1.0 <= velocity <= C):
    raise ValueError(f'velocity must be in [1, {C}] m/s, got {velocity}')
beta(velocity)

Try / catch

try:
    beta(v)
except ValueError as e:
    if 'exceed' in str(e):
        v = min(v, 299_792_458.0)  # clamp FTL input
    else:
        raise

Prevention

When it happens

Trigger: beta(3e8) or any velocity > 299792458; passing velocity in km/s or units of c (e.g. beta(0.9) is fine because it is < 1, but beta(2) interpreted as 2c in natural units is 2 m/s here and hits the other branch).

Common situations: Unit mismatch — velocity supplied in km/s (values look small) or in fractions of c multiplied by the wrong constant; sci-fi or simulation scenarios with FTL speeds; accumulating numerical error pushing v slightly above c near the limit.

Related errors


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