Vladimir
Vladimir

Reputation: 151

Numpy zero-division in try-except block, which raises "RuntimeWarning: invalid value encountered in double_scalars" and strange results

Code

s = np.zeros(2)
try:
    a = s[0]/s[1]
except:
    a = 10.0
print(a)

raises warning as mentioned in the title of the question and prints nan. It's rather strange, isn't it? How can it be explained and corrected?

Upvotes: 3

Views: 2296

Answers (1)

Prune
Prune

Reputation: 77827

It appears that you expect a divide-by-zero exception. The run-time system doesn't work this way: you get a warning and a result of nan. Thus, your exception block doesn't get tripped. Instead, try this:

if s[1]:
    a = s[0] / s[1]
else:
    a = 10.0

Upvotes: 2

Related Questions