Michele
Michele

Reputation: 8753

Unexpected result from fibonacci series using Rcpp

I'm just starting to use Rcpp so sorry if I'm missing an easy step or something similar... I have 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);
  }'
)

Up to fibonacci(46) everything's 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 the above should be:

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

Do you get the same result?

Upvotes: 4

Views: 164

Answers (1)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

You are exceeding the maximum limit for signed integers (technically this would be a long int I guess). 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

Upvotes: 5

Related Questions