Unexpected result from a Fibonacci series using Rcpp

I'm just starting to use Rcpp , so sorry if I am missing a simple step or something like that ... I tried this from ?sourceCpp

 library(Rcpp) sourceCpp(code=' #include <Rcpp.h> // [[Rcpp::export]] int fibonacci(const int x) { if (x == 0) return(0); if (x == 1) return(1); return (fibonacci(x - 1)) + fibonacci(x - 2); }' ) 

Before fibonacci(46) everything is fine, but then I get:

 > fibonacci(47) [1] -1323752223 > fibonacci(48) [1] 512559680 > fibonacci(49) [1] -811192543 > fibonacci(50) [1] -298632863 

According to this page above:

 47 : 2971215073 48 : 4807526976 49 : 7778742049 50 : 12586269025 

Do you get the same result?

+4
source share
1 answer

You are exceeding the maximum limit for signed integers (technically it will be a long int , I think). Use double instead.

 library(Rcpp) sourceCpp(code=' #include <Rcpp.h> // [[Rcpp::export]] double fibonacci(const double x) { if (x == 0) return(0); if (x == 1) return(1); return (fibonacci(x - 1)) + fibonacci(x - 2); }' ) fibonacci(47) #[1] 2971215073 
+5
source

Source: https://habr.com/ru/post/1502859/


All Articles