Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::isfinite on MSVC

The C++11 and C11 standard define the std::isfinite function. Visual Studio 2012 doesn't seem to provide it as part of the cmath or math.h, but has amp_math.h which seems to provide this function.

Is the isfinite interchangeable with std::isfinite? The documentation doesn't talk about the behavior when called with NAN and I don't have a VS compiler to test this.

like image 903
pmr Avatar asked Jan 29 '13 10:01

pmr


1 Answers

As Marius has already pointed out, the isfinite from amp_math.h is to be used in C++ AMP, which is an MS extension for parallel computing on many-core architectures similar to CUDA or OpenCL. And since this function can only be used in actual AMP restricted functions (usually GPU kernels) it won't be of much general use for you.

Unfortunately VS 2012 doesn't support the C++11 math and floating point control functions. But once you recognize that you are on VC and implement special code for it, you can just use _finite (or rather !_finite) from <float.h>, which is an MS-secific function supported since at least VS 2003. But keep in mind that _finite only takes doubles and thus converts any non-double arguments (though VC doesn't seem to have a proper long double anyway), with all its implications (while INFs and quiet NaNs should be converted without problem, I'm not sure if the trapping on a signalling NaN in the conversion would also have resulted from a direct call to std::finite).

VC's standard library has other such functions to accomodate for their lack of C++11/C99 support (like _isnan and the like). (Why they refuse to just remove that underscore in front of those functions and put a simple <cfenv> wrapper around _controlfp and thus get a bit nearer to complete C++11 support is a totally different question though.)

EDIT: Other than that, the straight-forward approach for checking INFs and NaNs might also work:

template<typename T> bool isfinite(T arg)
{
    return arg == arg && 
           arg != std::numeric_limits<T>::infinity() &&
           arg != -std::numeric_limits<T>::infinity();
}

But of course with the same implications of probably trapping for signalling NaNs (though I have to admit I'm not that well-versed in the intricacies of signalling NaNs and floating point exceptions in general).

like image 51
Christian Rau Avatar answered Sep 28 '22 10:09

Christian Rau