2

the IEEE Standard for Floating-Point Arithmetic (IEEE 754) requires the existence of a float (or two...) that is called nan (not a number).

there are two ways to get nan (that i know of)

nan = float("nan")
#  or
from math import nan

but is there a mathematical function i can perform on floats in the standard library that returns nan?

the obvious ideas like math.sqrt(-1) (and similar) do not return nan but raise ValueError: math domain error.

or are nans only meant for data where values are missing and are never supposed to be returned by a function?

(is there also something that returns math.inf? again, the obvious 1/0 raises a ZeroDivisionError).

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • 1
    "but is there a function or an operation i can perform on floats in the standard library that returns nan?" I don't understand how there is a question. You already showed two ways that do not require a third-party library. "or are nans only meant for data where values are missing and are never supposed to be returned by a function?" If the question is supposed to be "why is there such a thing as `nan` defined in the standard?", I am pretty sure that is already explained **by the standard**. – Karl Knechtel Feb 23 '23 at 15:05
  • 1
    not what i mean. should probably rephrase... is there e.g. a mathematical operation that returns `nan`? or a mathematical function in the stdlib? that may be more precise. my examples are not function calls (well `float` is but that is a special case...) – hiro protagonist Feb 23 '23 at 15:07
  • FWIW, you can also directly "reinterpret" raw data using the `struct` module. For example, using the half-float format for compactness, `struct.unpack('e', b'\x00~')` gives inf, and `struct.unpack('e', b'\x00|')` gives nan. However, I don't think that meets your requirements. – Karl Knechtel Feb 23 '23 at 15:24

2 Answers2

4

math.inf - math.inf gives nan.

(1e308 + 1e308 or just 1e309 give inf.)

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
3

Generating NaN:

  • math.inf * 0 results to nan

(+∞) × 0 = NaN

  • + (on opposite signs) and / (on any sign) operations between math.infs

  • and bonus case: generating 2 nans:

    In [576]: divmod(math.inf, 1)
    Out[576]: (nan, nan)
    
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105