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()
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
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
548 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
547 Who developed the "avformat-59.dll" that comes with FFmpeg?
711 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
537 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.