TheAlgorithms/Python · error · ValueError

Step size must be positive.

Error message

Step size must be positive.

What it means

Raised by the AdamsBashforth dataclass __post_init__ in maths/numerical_analysis/adams_bashforth.py when step_size <= 0. The solver advances the ODE solution in increments of step_size; a zero or negative step is physically meaningless and would loop forever or march backwards, so the constructor rejects it before any stepping method runs.

Source

Thrown at maths/numerical_analysis/adams_bashforth.py:59

    Traceback (most recent call last):
        ...
    ValueError: Step size must be positive.
    """

    func: Callable[[float, float], float]
    x_initials: list[float]
    y_initials: list[float]
    step_size: float
    x_final: float

    def __post_init__(self) -> None:
        if self.x_initials[-1] >= self.x_final:
            raise ValueError(
                "The final value of x must be greater than the initial values of x."
            )

        if self.step_size <= 0:
            raise ValueError("Step size must be positive.")

        if not all(
            round(x1 - x0, 10) == self.step_size
            for x0, x1 in zip(self.x_initials, self.x_initials[1:])
        ):
            raise ValueError("x-values must be equally spaced according to step size.")

    def step_2(self) -> np.ndarray:
        """
        >>> def f(x, y):
        ...     return x
        >>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_2()
        array([0.  , 0.  , 0.06, 0.16, 0.3 , 0.48])

        >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_2()
        Traceback (most recent call last):
            ...
        ValueError: Insufficient initial points information.

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a positive step: AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1.0).
  2. Compute step_size = (x_final - x_initials[-1]) / n with n a positive int and verify it is > 0.
  3. To integrate backwards, transform the ODE (substitute t -> -t) instead of using a negative step.

Example fix

# before
AdamsBashforth(f, [0, 0.2], [0, 0], 0, 1.0)

# after
AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1.0)
Defensive patterns

Strategy: validation

Validate before calling

if step_size <= 0:
    raise ValueError('step_size must be > 0')
# or derive: step_size = (x_final - x_initials[-1]) / n  (n positive int)

Prevention

When it happens

Trigger: AdamsBashforth(f, [0, 0.2], [0, 0], 0, 1) or any negative step_size; also step_size computed as (x_final - x0)/n where n overflows to 0 or the numerator has the wrong sign.

Common situations: step_size derived from a division that yields 0 (e.g. int truncation), sign errors when integrating 'backwards' (this API does not support negative steps), or config defaults left at 0.

Related errors


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