Fix NumPy RuntimeWarning: Divide by Zero in log()

Quick Answer

NumPy emits this warning because log(0) is -inf. Filter positive values when zeros are invalid, use a mask with a placeholder when shape must stay unchanged, or use np.errstate() only when -inf is an intentional result.

NumPy log visual showing zero inputs becoming negative infinity and safe handling paths
A logarithm pipeline must define what zero means before it filters, replaces, or preserves the value.

RuntimeWarning: divide by zero encountered in log appears when NumPy evaluates np.log() on zero. Mathematically, the natural log of zero is not a finite number, so NumPy returns -inf and emits a warning.

The warning is not always a crash, but it is still important. It tells you that your output contains an infinite value. The right fix depends on the data: filter non-positive values, replace zeros with a safe lower bound, or explicitly allow -inf when that is meaningful for your calculation.

This warning is common in data analysis because real datasets often use zero for missing counts, empty measurements, or true zero values. Those cases should not all be treated the same way.

Why the Warning Happens

np.log() is vectorized, so it applies the logarithm to every element in the array. Any zero value produces -inf and triggers the warning.

import numpy as np

values = np.array([0.0, 1.0, 10.0])

logged = np.log(values)
print(logged)

The result contains -inf for the zero element. If later code expects finite values only, that -inf can break plots, statistics, model inputs, or comparisons. The warning gives you a chance to handle those rows before they spread through the pipeline.

Python Pool infographic showing NumPy array, log function, zero input, negative infinity, and RuntimeWarning
NumPy log of zero produces negative infinity and can emit a divide-by-zero warning.

Filter Positive Values Before log()

If zero and negative values should not be included, filter the array before calling np.log(). This is often the cleanest fix for measurements that must be positive.

import numpy as np

values = np.array([0.0, 1.0, 10.0])

positive = values[values > 0]
logged = np.log(positive)

print(logged)

This avoids the warning because np.log() receives only positive values. Use this approach when removing zeros is consistent with the meaning of the data. If you need to preserve row alignment with another array, use a mask or placeholder instead of dropping elements.

Use np.where() to Keep the Original Shape

Sometimes the result must keep the same shape as the original array. Use np.where() to calculate logs only for valid values and store a placeholder elsewhere.

import numpy as np

values = np.array([0.0, 1.0, 10.0])

logged = np.where(values > 0, np.log(values), np.nan)
print(logged)

This keeps three output values. Invalid positions become nan, which is often easier to detect and handle later than a warning during calculation. A placeholder also makes it clear which inputs were not valid for logarithms.

Python Pool infographic mapping array values through positive-value mask before NumPy log calculation
Validate or mask values before taking a logarithm when zero and negative inputs are not meaningful.

Add a Small Epsilon Only When Appropriate

Some numeric workflows add a small positive value before taking the log. This avoids zero, but it changes the data, so use it only when the transformation is mathematically justified.

import numpy as np

values = np.array([0.0, 1.0, 10.0])
epsilon = 1e-9

logged = np.log(values + epsilon)
print(logged)

This is common in machine learning preprocessing, but it should not be used blindly. Document why the epsilon is acceptable for your dataset. If zero is a meaningful value rather than a measurement limit, adding epsilon may distort the analysis.

Use np.errstate() When -inf Is Expected

If -inf is an expected and acceptable result, use np.errstate() to control the warning locally. This keeps the warning policy close to the calculation.

import numpy as np

values = np.array([0.0, 1.0, 10.0])

with np.errstate(divide="ignore"):
    logged = np.log(values)

print(logged)

Do not use errstate() just to hide a problem. Use it when downstream code intentionally handles infinite values. Keeping the context manager small prevents other warnings from being hidden accidentally.

Python Pool infographic showing NumPy errstate context, log operation, warning policy, and output
errstate can control how NumPy floating-point warnings are handled, but it does not make invalid values valid.

Clean Infinite Results Afterward

If you already have the log result, check for finite values with np.isfinite(). This lets you keep or replace only valid results.

import numpy as np

values = np.array([0.0, 1.0, 10.0])

with np.errstate(divide="ignore"):
    logged = np.log(values)

finite_logged = logged[np.isfinite(logged)]
print(finite_logged)

This is useful when logs are one step in a larger pipeline. PythonPool’s NumPy log() guide covers related logarithm examples, and NumPy divide() covers another common warning family.

What Not to Do

Avoid suppressing the warning globally without checking the result. Global warning filters can hide unrelated numeric problems. Prefer a mask, a documented epsilon, or a small np.errstate() block around the one operation that expects zeros.

Python Pool infographic testing zero, negative values, NaN, infinity, dtype, and validation
Check the domain, NaN and infinity propagation, dtype, warning policy, and downstream handling.

Checklist

  • Use a positive-value mask when zeros should be excluded.
  • Use np.where() when the output shape must stay the same.
  • Use an epsilon only when changing zeros is mathematically acceptable.
  • Use np.errstate() only when infinite results are expected and handled.

Before choosing a fix, decide what zero means in your data. A true zero measurement, a missing value, and a placeholder all need different handling. Counting invalid values with tools like NumPy count_nonzero() can help quantify the problem before transforming the array.

The safest workflow is to inspect the input distribution, choose a missing-value policy, and then apply the log transform. That is better than suppressing the warning globally.

References

Choose a Zero-Value Policy Before Suppressing Warnings

Do not treat every zero as the same kind of problem. A true measurement, a missing-value placeholder, and an invalid sensor reading need different policies. Inspect the count and meaning of zero values first, then make the policy visible in code.

import numpy as np

values = np.array([0.0, 1.0, 10.0])
valid = values > 0
logged = np.full(values.shape, np.nan, dtype=float)
logged[valid] = np.log(values[valid])
print(logged)

This masked assignment preserves row alignment and avoids evaluating log() on zero. It is often clearer in production pipelines than globally ignoring floating-point warnings.

Frequently Asked Questions

What does log(0) return in NumPy?

NumPy returns negative infinity for log(0) and emits a divide by zero RuntimeWarning. The warning indicates that the result contains -inf.

How can I keep the original array shape?

Create a mask for positive values, allocate an output filled with a placeholder such as np.nan, and assign np.log() only to valid positions.

Should I add epsilon before np.log() by default?

No. Add epsilon only when changing zero to a small positive value is mathematically appropriate for the specific model or transformation.

When is np.errstate(divide=ignore) appropriate?

Use it locally when infinite results are expected and downstream code explicitly handles them. It should not replace checking the output for invalid values.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted