Equal to operator ==, can be used to check a bit?

What is the purpose of the function?

bool whatIsIt(double n) { return n == n; } 

Can it be used to check every bit in n?

I doubt it.

Any comments are welcome.

+4
source share
5 answers

It can be used to check if n is NaN (and not a number), since NaN is not compared with itself.

This is probably a fictitious and not entirely reliable way to do this. (see various comments by Billy). C99 and C ++ 11 have the isnan() function.

+11
source

This is indicated in standard C in floating-point arithmetic of Appendix F: 60559, in particular F.8.3. Relationship Operators:

... The statement x != x true if x is NaN

... The statement x == x is not true if x is NaN

If __STDC_IEC_559__ is #defined , then this function will return false if n is NaN .

+4
source

Probably there NaNs were found there (which are no different from each other), although this depends on your specific compiler / platform / settings, etc. The standard, strictly speaking, does not talk about how floating point math is handled.

+2
source

No, this is not a โ€œbit checkโ€.

I guess it checks for "NaN". It will return FALSE if the input is NaN, and will return TRUE if it is a different floating point value.

0
source

This function checks that the number is comparable.

This can be very important for values โ€‹โ€‹used as a key to a sort function or used in a search. The comparison used in sorting assumes that if A <B is true, then B <A will be false. If A or B is an incomparable value, both of these statements will be false.

Technically, what type is required is called strict weak order .

An item in the collection that has an incomparable value cannot be found. A list containing an incomparable value is not sortable. In addition, an optimized implementation may exit the array, which will be sorted and begin to corrupt memory or never complete.

The only disparate value that I know for the double is NaN. As others have pointed out, NaN will return false if used as the parameter whatIsIt() . If NaN is a possible value for the numbers you are comparing, then you have to handle it, or bad things can happen.

Problems with std :: map and NaN are mentioned in this wikipedia article.

You can build a comparison to sort NaN at a given place in the list, but you cannot do this only with the built-in operators. Instead, you would do something like

 if ( A < B ) then return -1; else if ( B < A ) then return 1; else return whatIsIt(A) - whatIsIt(B); 

Aside, in SQL, NULL also cannot be compared in compatible implementations.

The secret is why isnan () was not used unless it was an interview question or something like that.

0
source

All Articles