17.1 C
London
Saturday, July 26, 2025
HomePythonFix Common Errors in PythonHow to Fix: invalid value encountered in true_divide

How to Fix: invalid value encountered in true_divide

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

One warning you may encounter when using NumPy is:

RuntimeWarning: invalid value encountered in true_divide

This warning occurs when you attempt to divide by some invalid value (such as NaN, Inf, etc.) in a NumPy array.

It’s worth noting that this is only a warning and NumPy will simply return a nan value when you attempt to divide by an invalid value.

The following example shows how to address this warning in practice.

How to Reproduce the Error

Suppose we attempt to divide the values in one NumPy array by the values in another NumPy array:

import numpy as np

#define NumPy arrays
x = np.array([4, 5, 5, 7, 0])
y = np.array([2, 4, 6, 7, 0])

#divide the values in x by the values in y
np.divide(x, y)

array([2.    , 1.25  , 0.8333, 1.    ,    nan])

RuntimeWarning: invalid value encountered in true_divide

Notice that NumPy divides each value in x by the corresponding value in y, but a RuntimeWarning is produced.

This is because the last division operation performed was zero divided by zero, which resulted in a nan value.

How to Address this Warning

As mentioned earlier, this RuntimeWarning is only a warning and it didn’t prevent the code from being run. 

However, if you’d like to suppress this type of warning then you can use the following syntax:

np.seterr(invalid='ignore')

This tells NumPy to hide any warning with some “invalid” message in it.

So, if we run the code again then we won’t receive any warning:

import numpy as np

#define NumPy arrays
x = np.array([4, 5, 5, 7, 0])
y = np.array([2, 4, 6, 7, 0])

#divide the values in x by the values in y
np.divide(x, y)

array([2.    , 1.25  , 0.8333, 1.    ,    nan])

A nan value is still returned for the last value in the output, but no warning message is displayed this time.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix KeyError in Pandas
How to Fix: ValueError: cannot convert float NaN to integer
How to Fix: ValueError: operands could not be broadcast together with shapes

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories