How to check for inf (and | or) NaN in a double variable
When using
scanf()
double
should be read using%lf
, not%f
.%f
will convert the input into a 32-bitfloat
, so the first 32 bits of your variables will be filled with some invalid data, and the last 32 bits will be left as garbage.Yes.
#include <limits>
, thenstd::numeric_limits<double>::quiet_NaN()
. Some compilers (e.g. gcc) also provides theNAN
macro in<cmath>
.There is no NaN or infinity for integer types. Divide-by-zero for integer will cause an exception (SIGFPE).
#include <cmath>
, thenstd::isinf(x)
. Usestd::isfinite(x)
to ensurex
is not NaN or Infinity.
Check if a number is +-Inf or NaN
C99 has macros for the classification of floating-point numbers:
fpclassify(x)
returns one of:
FP_NAN
:x
is not a number;FP_INFINITE
:x
is plus or minus infinite;FP_ZERO
:x
is zero;FP_SUBNORMAL
:x
is too small to be represented in normalized format orFP_NORMAL
: normal floating-point number, i.e. none of the above.
There are also shortcuts that check for one of these classes, which return non-zero if x
is what :
isfinite(x)
isnormal(x)
isnan(x)
isinf(x)
The argument x
can be any floating-point expression; the macros detect the type of the argument and work for float
and double
.
EDIT: Since you don't want to use (or cannot use) <math.h>
, you could use other properties of nan and inf to classify your numers:
nan
compares false to all numbers, including to itself;inf
is greater thanFLT_MAX
;-inf
is smaller than-FLT_MAX
.
So:
#include <stdlib.h>
#include <stdio.h>
#include <float.h>
int main()
{
float f[] = {
0.0, 1.0, FLT_MAX, 0.0 / 0.0, 1.0/0.0, -1.0/0.0
};
int i;
for (i = 0; i < 6; i++) {
float x = f[i];
int is_nan = (x != x);
int is_inf = (x < -FLT_MAX || x > FLT_MAX);
printf("%20g%4d%4d\n", x, is_nan, is_inf);
}
return 0;
}
In this solution, you must adapt the limits if you want to use double
.
How to use nan and inf in C?
You can test if your implementation has it:
#include <math.h>
#ifdef NAN
/* NAN is supported */
#endif
#ifdef INFINITY
/* INFINITY is supported */
#endif
The existence of INFINITY
is guaranteed by C99 (or the latest draft at least), and "expands to a constant expression of type float representing positive or unsigned
infinity, if available; else to a positive constant of type float that overflows at translation time."
NAN
may or may not be defined, and "is defined if and only if the implementation supports quiet NaNs for the float type. It expands to a constant expression of type float representing a quiet NaN."
Note that if you're comparing floating point values, and do:
a = NAN;
even then,
a == NAN;
is false. One way to check for NaN would be:
#include <math.h>
if (isnan(a)) { ... }
You can also do: a != a
to test if a
is NaN.
There is also isfinite()
, isinf()
, isnormal()
, and signbit()
macros in math.h
in C99.
C99 also has nan
functions:
#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);
(Reference: n1256).
Docs INFINITY
Docs NAN
Shortest way of checking if Double is NaN
As MSDN says, NaN means that result is undefined. With infinities result is defined:
A method or operator returns NaN when the result of an operation is
undefined. For example, the result of dividing zero by zero is NaN, as
the following example shows. (But note that dividing a non-zero number
by zero returns either PositiveInfinity or NegativeInfinity, depending
on the sign of the divisor.)
So, it's not good idea to tread infinities as NaN. You can write extension method to check if value is not NaN or infinity:
// Or IsNanOrInfinity
public static bool HasValue(this double value)
{
return !Double.IsNaN(value) && !Double.IsInfinity(value);
}
How do you test to see if a double is equal to NaN?
Use the static Double.isNaN(double)
method, or your Double
's .isNaN()
method.
// 1. static method
if (Double.isNaN(doubleValue)) {
...
}
// 2. object's method
if (doubleObject.isNaN()) {
...
}
Simply doing:
if (var == Double.NaN) {
...
}
is not sufficient due to how the IEEE standard for NaN and floating point numbers is defined.
How can I check for NaN values?
Use math.isnan
:
>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True
Checking if a double (or float) is NaN in C++
According to the IEEE standard, NaN values have the odd property that comparisons involving them are always false. That is, for a float f, f != f
will be true only if f is NaN.
Note that, as some comments below have pointed out, not all compilers respect this when optimizing code.
For any compiler which claims to use IEEE floating point, this trick should work. But I can't guarantee that it will work in practice. Check with your compiler, if in doubt.
How do you check for infinite and indeterminate values in C++?
For Visual Studio I would use _isnan
and _finite
, or perhaps _fpclass
.
But if you have access to a C++11-able standard library and compiler you could use std::isnan
and std::isinf
.
How do you check that a number is NaN in JavaScript?
Try this code:
isNaN(parseFloat("geoff"))
For checking whether any value is NaN, instead of just numbers, see here: How do you test for NaN in Javascript?
Related Topics
In C++, Is a Function Automatically Virtual If It Overrides a Virtual Function
C++ Access to SQL Server from Linux
Forcing a Constant Expression to Be Evaluated During Compile-Time
Check If Two Types Are Equal in C++
Redirecting Function Output to /Dev/Null
How to Define Thread-Local Local Static Variables
Tool to Generate Xml File from Xsd (For Testing)
How Could I Sensibly Overload Placement Operator New
Addresses of Identical Function Template Instantiations Across Compilation Units
Template Metaprogramming: (Trait For) Dissecting a Specified Template into Types T<T2,T3 N,T4, ...>
Why Does Std::Map Not Have a Const Accessor
Constructor with By-Value Parameter & Noexcept
Visual Studio Compiler Warning C4250 ('Class1':Inherits 'Class2::Member' via Dominance)