Peeter Joot's (OLD) Blog.

Math, physics, perl, and programming obscurity.

strange looking predicate!

Posted by peeterjoot on July 6, 2011

The following code fragment was suggested today by a compiler guru as a way of checking for a floating point overflow or underflow:

double tmp = foo() ;

if ( tmp - tmp != tmp - tmp) 
   // handle floating point overflow or underflow.

Apparently, this works (at least for one compiler) because if tmp is +inf or -inf, subtracting it to itself will return NaN, which compares different to itself!

It will be interesting to see if this works on more than one compiler and in both optimized and debug build modes.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: