float or double validity

I

Imre Ament

Hi,

I have to test double and float values before write it to a database.
I found the '_fpclass' function and consider its return value:

parameter was an owerflowed (wrong) double
_FPCLASS_SNAN /* signaling NaN */
_FPCLASS_QNAN /* quiet NaN */
_FPCLASS_NINF /* negative infinity */
_FPCLASS_PINF /* positive infinity */

parameter was a valid (x >= DBL_MIN and x <= DBL_MAX) number
_FPCLASS_NN /* negative normal */
_FPCLASS_ND /* negative denormal */
_FPCLASS_NZ /* -0 */
_FPCLASS_PZ /* +0 */
_FPCLASS_PD /* positive denormal */
_FPCLASS_PN /* positive normal */

1. I am right?
2. How can I manage this test on a 'float' number?
('_fpclass' has type of 'double' parameter and I mean to call it with a
'float' does not a good practise,
because casting a wrong float to a double may results a valid number)

Regards,
Imre
 
T

Tamas Demjen

I have to test double and float values before write it to a database.
I found the '_fpclass' function and consider its return value:

Boost has fpclassify<T>, which should work with float as well as double:
http://www.boost.org/doc/libs/1_41_0/libs/math/doc/sf_and_dist/html/math_toolkit/utils/fpclass.html

First
#include <boost/math/special_functions/fpclassify.hpp>.

then simply call
if(boost::math::isnan(f) || boost::math::isinf(f))
// error

That's properly tested on multiple platforms.

Otherwise you could write your own function:

#include <limits>

// don't let the windows.h macros conflict
#undef min
#undef max

template <typename T>
bool IsValid(T f)
{
if(f != f)
return false; // NaN
else if(f > std::numeric_limits<T>::max() ||
f < -std::numeric_limits<T>::max())
return false; // INFINITY or -INFINITY
else
return true;
}

The compiler should never optimize away the `if(f != f)' for float and
double types, but in case it does, make it `volatile T f'.

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top