Home > front end >  What determines whether numpy returns NAN or INF upon divide-by-zero
What determines whether numpy returns NAN or INF upon divide-by-zero

Time:03-30

Im trying to understand the following results:

In [1]: with np.errstate(divide='ignore', invalid='ignore'):
    ...:     for val in 1e-324,2e-324,3e-324:
    ...:         val_by_zero = np.array([val])/0
    ...:         print( val_by_zero, np.nan_to_num(val_by_zero))
    ...:
    ...:
[nan] [0.]
[nan] [0.]
[inf] [1.79769313e 308]


In [2]: np.__version__
Out[2]: '1.20.3'

In [3]: np.finfo(np.float64)
Out[3]: finfo(resolution=1e-15, min=-1.7976931348623157e 308, max=1.7976931348623157e 308, dtype=float64)

I am just curious exactly whats going on in within the numpy library that determines whether a float is inf or nan.

This is python 3.8.12 running on CentOS Linux release 7.9.2009.

NOTE: I arrived at the numbers vals=[1e-324, 2e-324, 3e-324] after inspecting an application that was corrupted by unwanted large numbers (e.g. the float max 1.79769313e 308). I imagine that these vals are platform and/or configuration dependent.

CodePudding user response:

The first positive number that can be represented by float64 is 5e-324.

from numpy import nextafter
nextafter(0, 1)
# Out: 5e-324

1e-324 and 2e-324 are closer to 0 so they are so they are represented as 0 but 3e-324 is closer to 5e-324 so it is represented as 5e-324.

np.array([1e-324, 2e-324, 3e-324])
# Out: array([0.e 000, 0.e 000, 5.e-324])

At this point it basically boils down to positive number / 0 vs 0 / 0. The former is infinity while the latter is undefined.

  • Related