TheAlgorithms/Java · error · IllegalArgumentException

Gravity must be positive

Error message

Gravity must be positive

What it means

Thrown by the SimplePendulumRK4 constructor when g <= 0. The gravitational acceleration g appears in omega = sqrt(g / L) and drives the restoring torque; a non-positive g makes the pendulum non-oscillatory or undefined. This is the second guard, checked after the length guard.

Source

Thrown at src/main/java/com/thealgorithms/physics/SimplePendulumRK4.java:29

    private SimplePendulumRK4() {
        throw new AssertionError("No instances.");
    }

    private final double length; // meters
    private final double g; // acceleration due to gravity (m/s^2)

    /**
     * Constructs a simple pendulum simulator.
     *
     * @param length the length of the pendulum in meters
     * @param g the acceleration due to gravity in m/s^2
     */
    public SimplePendulumRK4(double length, double g) {
        if (length <= 0) {
            throw new IllegalArgumentException("Length must be positive");
        }
        if (g <= 0) {
            throw new IllegalArgumentException("Gravity must be positive");
        }
        this.length = length;
        this.g = g;
    }

    /**
     * Computes the derivatives of the state vector.
     * State: [theta, omega] where theta is angle and omega is angular velocity.
     *
     * @param state the current state [theta, omega]
     * @return the derivatives [dtheta/dt, domega/dt]
     */
    private double[] derivatives(double[] state) {
        double theta = state[0];
        double omega = state[1];
        double dtheta = omega;
        double domega = -(g / length) * Math.sin(theta);
        return new double[] {dtheta, domega};

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass a strictly positive g in m/s^2 (9.81 Earth, 1.62 Moon, 3.71 Mars).
  2. Make g a named constant or config value with validation at load time.
  3. If switching celestial bodies, ensure the g field is reassigned, not left at a 0 default.

Example fix

// before
SimplePendulumRK4 p = new SimplePendulumRK4(1.0, 0);
// after
SimplePendulumRK4 p = new SimplePendulumRK4(1.0, 9.81);
Defensive patterns

Strategy: validation

Validate before calling

if (Double.isNaN(g) || g <= 0) {
    throw new IllegalArgumentException("g must be > 0");
}
SimplePendulumRK4 p = new SimplePendulumRK4(length, g);

Prevention

When it happens

Trigger: Calling new SimplePendulumRK4(length, g) with g == 0 or a negative g. Using g of exactly 0 models free-fall (no oscillation) and is rejected; ~9.81 m/s^2 is the Earth-surface convention.

Common situations: Config defaulting g to 0, modelling a different body but forgetting to set g (leaving 0), or a unit error (g given in cm/s^2 and then divided).

Related errors


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