Created
March 17, 2011 03:47
-
-
Save malkia/873800 to your computer and use it in GitHub Desktop.
This examples show how floating point numbers that are NaN are always different even if they are the same binary identity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
/* | |
malkia ~/p $ gcc nan.c | |
nan.c: In function ‘print_range’: | |
nan.c:15: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘unsigned int’ | |
nan.c:15: warning: format ‘%p’ expects type ‘void *’, but argument 3 has type ‘unsigned int’ | |
nan.c:15: warning: format ‘%p’ expects type ‘void *’, but argument 4 has type ‘unsigned int’ | |
malkia ~/p $ ./a.out | |
[0x7f800001 .. 0x7fffffff], total of 0x7fffff (8388607) | |
[0xff800001 .. 0xffffffff], total of 0x7fffff (8388607) | |
*/ | |
union { | |
float f; | |
unsigned u; | |
} n; | |
/* | |
The following would make NaN not happy :) | |
-ffast-math | |
-ffinite-math-only | |
*/ | |
void print_range( unsigned first, unsigned last ) | |
{ | |
printf( "[%p .. %p], total of %p (%d)\n", first, last, last - first + 1, last - first + 1 ); | |
} | |
int main() | |
{ | |
unsigned first_nan = 0, found_nan = 0; | |
// 0 is not a NaN so we start from 1 | |
// And use the fact that it would wrap | |
for( n.u=1; n.u; n.u++ ) { | |
// Is it a NaN number? | |
// A NaN number is never equal to itself | |
if( n.f != n.f ) { | |
if( !found_nan ) { | |
found_nan = 1; | |
first_nan = n.u; | |
} | |
continue; | |
} | |
if( found_nan ) { | |
print_range( first_nan, n.u - 1 ); | |
found_nan = 0; | |
} | |
} | |
if( found_nan ) { | |
print_range( first_nan, n.u - 1 ); | |
found_nan = 0; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment