Software:
News ToolsReg Shops |
Unequal equivalenceWhen is a number not a number?Published Monday 16th January 2006 16:02 GMT When is a number not a number?In the world of floating-point numbers there is commonly a notion of a special value that represents something that is not a number, NaN for short. A NaN value has some interesting properties: it does not order against any other value, and does not even compare equal to itself. Alas, one problem with having "interesting properties" is that, left to its own devices, a NaN rather messes up the idea of a total ordering that can be used for sorting. Because Java's type system is not fully object oriented there is a divorce between what can be done with primitive types, such as C#, by contrast, has a more regular type system, one that incorporates primitive types as first class types in its object system. Wrapper types are not needed, so In C++ ordering is defined, by default, in terms of the < operator rather than via a separate operation granted by an inherited class. This effectively offers the same behaviour as the corresponding operator in C# and Java, which means that because of NaN it doesn't offer a total ordering on all floating-point values. To understand what this means in practice, consider holding a set of However, all is not lost. You can impose your own preferred ordering criterion through a function object type, i.e. a class whose instances look like functions because they can be invoked with the function-call operator. The following type imposes an ordering so that a NaN is considered lower than any proper value:
struct total_less
{
template<typename numeric_type>
bool operator()(numeric_type lhs, numeric_type rhs) const
{
return is_nan(lhs) ? !is_nan(rhs) : lhs < rhs;
}
};
To use this with a The
template<typename numeric_type>
bool is_nan(numeric_type value)
{
return !(value == value);
}
This is generic and works for any numeric type, so consequently total_less will also work for any numeric type. ® This article originally appeared in Application Development Advisor. Kevlin Henney is an independent software development consultant and trainer. He can be reached at http://www.curbralan.com.
Track this type of story as a custom Atom/RSS feed or by email.
|
Developer HeadlinesThe UK's latest developer news from MSDN |
Top 20 stories • All The Week’s Headlines • Archive • Search