[Rcpp-devel] Rcpp catching a domain error

Qiang Kou qkou at umail.iu.edu
Fri Dec 12 15:35:22 CET 2014


Hi, Devin,

You may misunderstand NaN. NaN is a special floating number. It doesn't
equal to anything, even itself. If x is NaN, x == x will return false.
Actually this is a trick to detect whether it is NaN or not.

However, there is a standard way to handle it, using isnan [1]. Try the
code below:

// [[Rcpp::depends(RcppGSL)]]
#include <RcppGSL.h>
#include <gsl/gsl_sf_hyperg.h>

#include <Rcpp.h>
#include <math.h>
using namespace Rcpp;

// [[Rcpp::export]]
SEXP test()
{
    gsl_set_error_handler_off();
    double res = gsl_sf_hyperg_2F1(1,1,1.1467003,1);
    if (res != res){
Rcout << "NaN found!" << std::endl;
}
 if (isnan(res)){
Rcout << "NaN found using isnan!" << std::endl;
}
    return R_NilValue;
}

R result:

> sourceCpp("testgsl.cpp")
> test()
NaN found!
NaN found using isnan!
NULL
>

If you are dealing with something more than a NaN floating number, Dirk's
solution is your best choice.

Best,

KK


[1]
http://www.gnu.org/software/libc/manual/html_node/Floating-Point-Classes.html#Floating-Point-Classes

On Fri, Dec 12, 2014 at 8:05 AM, Dirk Eddelbuettel <edd at debian.org> wrote:
>
>
> On 12 December 2014 at 10:09, Devin wrote:
> | ... but you can't set a mathematical operation equal to a string. I also
> tried:
> |
> | int test()
> | {
> |     gsl_set_error_handler_off();
> |     if(gsl_sf_hyperg_2F1(1,1,1.1467003,1) == NAN){
> |         std::cout << "Error" << std::endl;
> |     }
> |     return 0;
> | }
> |
> | ... but the if-branch gets ignored. How can I achieve that the program
> runs through the if-branch?
>
> Use a proper test for NaN.
>
> See eg http://gallery.rcpp.org/articles/working-with-missing-values/ or
> other
> documentation as eg the Writing R Extensions manual, my Rcpp book -- or the
> content of the Rcpp package.
>
> A simple way, using a macro from the R headers, is
>
>   R> cppFunction('bool isItNan(double foo) { return ISNAN(foo); }')
>   R> isItNan(NaN)
>   [1] TRUE
>   R> isItNan(3.14)
>   [1] FALSE
>   R> isItNan(3L)
>   [1] FALSE
>   R>
>
> There are (better) alternatives in the Rcpp sources, but some of the
> behaviour is subtle. Kevin once wrote a great answer at StackOverflow:
>
>
> http://stackoverflow.com/questions/26241085/rcpp-function-check-if-missing-value/26262984#26262984
>
>
> Dirk
>
> --
> http://dirk.eddelbuettel.com | @eddelbuettel | edd at debian.org
>


-- 
Qiang Kou
qkou at umail.iu.edu
School of Informatics and Computing, Indiana University
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20141212/2357c084/attachment.html>


More information about the Rcpp-devel mailing list