How to work with "RuntimeWarning: divide by zero encountered in log" on numpy

Asked 2 years ago, Updated 2 years ago, 350 views

In Python 3.10.7, when you move the following code, you see a warning for numpy_test.py:5:RuntimeWarning:divide by zero encountered in log.

numpy_test.py:5:RuntimeWarning:divide by zero encountered in log
np_ret=np.where(np_val<=0.5, np.sqrt(np_val), np.log(np_val))
[0.]

The print(ret_val) display is [0.], so we believe that np_func() returns the value of np.sqrt(0).
Therefore, when np.zeros(1) is passed to np_func(), not only the np.sqrt(np_val) that meets the conditions, but also the np.log(np_val) that does not meet the conditions are also warned. Do you understand?

If possible, I would like to ignore the warnings in the calculations that are not actually used, but is there any way?

import numpy as np


defnp_func(np_val):
    np_ret=np.where(np_val<=0.5, np.sqrt(np_val), np.log(np_val))
    return np_ret


def test_numpy():
    np_val = np.zeros(1)
    ret_val = np_func(np_val)
    print(ret_val)


if__name__=="__main__":
    test_numpy()

python3

2022-10-04 01:00

2 Answers

How to temporarily ignore

def np_func(np_val):
    with np.errstate(divide='ignore'):
        np_ret=np.where(np_val<=0.5, np.sqrt(np_val), np.log(np_val))
    return np_ret


2022-10-04 01:00

How about using the warnings module?
(additional) Context Manager available.

import warnings

import numpy as np


defnp_func(np_val):
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        np_ret=np.where(np_val<=0.5, np.sqrt(np_val), np.log(np_val))
    return np_ret

def test_numpy():
    np_val = np.zeros(1)
    ret_val = np_func(np_val)
    print(ret_val)


if__name__=="__main__":
    test_numpy()

Note: warnings---Control Warning/Python 3.10.6 document


2022-10-04 01:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.