All operations that will result in nan values(python)

Question:

This may be a simple question but i could not get all the answers in one place, so any help and answer are welcome 🙂 . I am trying to debug a program, But then I realize I don’t know what are all the possible operation that may result in a NAN value in python. so here is the question what are all the possible operations that will result in a nan value in python specifically numpy matrices?

An example will be like

x=float('nan')
x=x+x
print x

results in

nan
Asked By: gman

||

Answers:

NaNs are part of the IEEE 754 standards. Operation like but not limited to inf * 0, inf / inf or any operation involving a NaN, e.g. nan * 1, return a NaN.

http://en.wikipedia.org/wiki/IEEE_754-1985

Answered By: runDOSrun

In numpy land you often get nans for illegal mathematical operations. Consider

>>> from math import asin
>>> asin(1.1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

Similar operation in numpy yields a nan:

>>> from numpy import arcsin
>>> arcsin(1.1)
__main__:1: RuntimeWarning: invalid value encountered in arcsin
nan

Notice that by (python’s) default you only get a warning once.

When debugging, look for illegal operations, esp domain errors: divisions by zero, square roots of negative numbers etc.

A second major source of nans is indeterminate expressions of the form inf/inf, 0/0, 0*inf and so on.

Lastly, since nans are sticky (once you have a first nan in an expression, it propagates), when debugging you typically need to find the first operation which goes haywire.

Answered By: ev-br
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.