1

Given the following questions Divide by Zero Prevention and Check if it's a NaN as the examples I've written the folowing code:

#include <cstdlib>
#include <iostream>
#include <map>
#include <windows.h>
using namespace std;
bool IsNonNan( float fVal )
{ 
     return( fVal == fVal );
}

int main(int argc, char *argv[])
{
    int nQuota = 0;
    float fZero = 3 / (float)nQuota; 
    cout << fZero << endl;
    cout << IsNonNan( fZero ) << endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}

Why is IsNonNan returning true? also why would int nZero = 3 / (float)nQuota; output: -2147483648?

Community
  • 1
  • 1
Vinícius
  • 15,498
  • 3
  • 29
  • 53

3 Answers3

2

3 / 0 is +INF, not NaN. Try 0 / 0.

Keith Randall
  • 22,985
  • 2
  • 35
  • 54
  • But isn't #.INF a NaN? If it's not a NaN, how to check if a number is `pos inf` or `neg inf`? – Vinícius Jul 11 '12 at 22:34
  • http://stackoverflow.com/questions/570669/checking-if-a-double-or-float-is-nan-in-c Related. – Wug Jul 11 '12 at 22:37
1

Not, is not, NaN states for "Not a Number", it means, something that can't be expressed as a number (indeterminations like 0 / 0 which mathematically speaking, don't have a numeric representation), infinity, is just that, infinities, positive or negative

To check if a float is infinity, you can use:

inline bool IsInf(float fval)  {
    return (fval == fval) && ((fval - fval) != 0.0f);
}
higuaro
  • 15,730
  • 4
  • 36
  • 43
  • 2
    To check for infinity, one should use `std::isinf` from ``. The rest of your answer is mathematically unsound; infinity is not a number either in standard analysis. – Fred Foo Jul 11 '12 at 22:48
  • 1
    Yes, indeed (although I'm suspecting that (s?)he's leaning to implement it by h(im|er)self) – higuaro Jul 11 '12 at 22:54
0

int nZero = 3 / (float)nQuota; outputs -2147483648 because the conversion of 0 to float is value of <= 1e-009 which is given throughout float f = 0.000000001; or less.

Vinicius Horta
  • 233
  • 2
  • 13