TheAlgorithms/Java · error · IllegalArgumentException

Mass and radius must be positive.

Error message

Mass and radius must be positive.

What it means

Thrown by Gravitation.calculateCircularOrbitVelocity when centralMass <= 0 or radius <= 0. The formula v = sqrt(G * M / r) divides by radius and requires positive mass for a physically meaningful gravitational source; non-positive values would cause division by zero or an undefined square root. This computes the speed for a stable circular orbit around a massive body.

Source

Thrown at src/main/java/com/thealgorithms/physics/Gravitation.java:62

        // Calculate the components of the force vector
        double fx = forceMagnitude * (dx / distance);
        double fy = forceMagnitude * (dy / distance);

        return new double[] {fx, fy};
    }

    /**
     * Calculates the speed required for a stable circular orbit.
     *
     * @param centralMass The mass of the central body (kg).
     * @param radius The radius of the orbit (m).
     * @return The orbital speed (m/s).
     * @throws IllegalArgumentException if mass or radius are not positive.
     */
    public static double calculateCircularOrbitVelocity(double centralMass, double radius) {
        if (centralMass <= 0 || radius <= 0) {
            throw new IllegalArgumentException("Mass and radius must be positive.");
        }
        return Math.sqrt(GRAVITATIONAL_CONSTANT * centralMass / radius);
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass strictly positive centralMass (kg) and radius (m) — e.g. Sun mass 1.989e30 and Earth orbital radius 1.496e11.
  2. Validate astrophysical inputs at the data-load boundary and reject zero/negative mass or radius before the call.
  3. Double-check unit consistency (SI units kg and m are expected).

Example fix

// before
double v = Gravitation.calculateCircularOrbitVelocity(0, 1.496e11);
// after
double v = Gravitation.calculateCircularOrbitVelocity(1.989e30, 1.496e11);
Defensive patterns

Strategy: validation

Validate before calling

if (!(centralMass > 0 && radius > 0)) {
    throw new IllegalArgumentException("centralMass and radius must be > 0");
}
double v = Gravitation.calculateCircularOrbitVelocity(centralMass, radius);

Prevention

When it happens

Trigger: Calling calculateCircularOrbitVelocity(centralMass, radius) with centralMass = 0, a negative mass, radius = 0, or a negative radius.

Common situations: Unit-conversion errors producing zero (e.g. solar masses converted to kg with a wrong factor), reading a body from a catalogue where mass was absent and defaulted to 0, or a sign error in radius from a coordinate subtraction.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/fb88bde4f0d46dfc. Report an issue: GitHub.