WarningPython Error

RuntimeWarning

RuntimeWarning: divide by zero encountered in double_scalars

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    result = np.array([1, 0]) / np.array([0, 0])  # RuntimeWarning
RuntimeWarning: divide by zero encountered in double_scalars

What causes this error

A questionable runtime condition was detected. In numpy, this includes division by zero, overflow, and invalid mathematical operations on arrays.

How to fix it

For numpy: use `np.errstate()` to control warning behavior, handle inf/nan values with `np.isnan()` and `np.isinf()`. For coroutines: add missing `await`. Address the underlying numerical issue when possible.

Code that causes this error

Broken
import numpy as np
result = np.array([1, 0]) / np.array([0, 0])  # RuntimeWarning

Fixed code

Fixed
import numpy as np
with np.errstate(divide="ignore", invalid="ignore"):
    result = np.array([1, 0]) / np.array([0, 0])
    result = np.nan_to_num(result, nan=0.0, posinf=0.0)

About RuntimeWarning

A RuntimeWarning is issued for runtime conditions that are suspicious but not necessarily errors. In the standard library, RuntimeWarning appears for unawaited coroutines (discussed separately) and for certain floating-point edge cases. In numpy, RuntimeWarning is extensively used for operations like division by zero (which returns inf or nan instead of raising), log of zero, overflow, and invalid value in mathematical operations.

Unlike Python's strict ZeroDivisionError, numpy uses warnings to allow vectorized operations to continue rather than stopping on the first problematic element. The numpy `errstate` context manager allows you to control how these warnings are handled: ignore, warn, raise, call, or log. Understanding when RuntimeWarning appears in your numerical code is important for data quality.

Common scenarios

1

Using deprecated APIs that will be removed in future versions

2

Performing numerical operations that produce inf or NaN values

3

Leaving files, sockets, or connections open without proper cleanup

4

Calling async functions without awaiting the result

Related errors