10

How to check if a float number is a true number? That is: it is not infinity, negative infinity, NaN ...

float f;
???
user1899020
  • 13,167
  • 21
  • 79
  • 154
  • 2
    You mean functions like [`std::isnan`](http://en.cppreference.com/w/cpp/numeric/math/isnan)? That's C++11 but does the job. – tadman Jun 09 '16 at 15:33
  • 2
    Have you seen [std::isfinite](http://en.cppreference.com/w/cpp/numeric/math/isfinite) and the related functions? – James Adkison Jun 09 '16 at 15:34
  • you mean a *real* number? Because a number is true if it's different from 0.0 – phuclv Jun 09 '16 at 15:45
  • 1
    Please [edit](http://stackoverflow.com/posts/37730313/edit) your question to not use `...` and instead fully explain what aspects must be considered to meet your definition of _true_. – James Adkison Jun 09 '16 at 15:46

4 Answers4

11

Simpler than std::fpclassify() is to use std::isfinite()

Determines if the given floating point number arg has finite value i.e. it is normal, subnormal or zero, but not infinite or NaN.

eerorika
  • 232,697
  • 12
  • 197
  • 326
5

std::isnormal() does what you want but it also checks for 0.0. So you might check that case extra:

float f;
bool isNumber = (std::isnormal(f) || f == 0.0);

Edit: as pointed out by user2079303 isnormal also returns false for a subnormal number which the OP probably does not want.

However, maybe std::isfinite does the right thing.

float f;
bool isNumber = std::isfinite(f) ;

it returns false for NaN and Inf.

Community
  • 1
  • 1
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
1

For C++11 and onwards, use !std::isnan(f) && !std::isinf(f) to test for a number being neither NaN nor infinity (positive or negative).

Pre-C++11 it's a bit more difficult, but you can still do it. If your platform uses IEEE754 for the float then you can use:

  1. f == f will be false only for the NaN case.

  2. Something of the form f == f / 2 will be true only for infinity or a number close to zero, and you can trivially eliminate the latter case.

Boost (www.boost.org) also provides methods for pre C++11. See http://www.boost.org/doc/libs/1_41_0/libs/math/doc/sf_and_dist/html/math_toolkit/utils/fpclass.html

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

std::fpclassify() looks like what you are looking for.

int fpclassify( float arg );
int fpclassify( double arg );
int fpclassify( long double arg );
int fpclassify( Integral arg );

Return value

one of FP_INFINITE, FP_NAN, FP_NORMAL, FP_SUBNORMAL, FP_ZERO or implementation-defined type, specifying the category of arg.

DevSolar
  • 67,862
  • 21
  • 134
  • 209