斐波那契系列使用Rcpp的意外结果

Mic*_*ele 4 r rcpp

我只是开始使用Rcpp,如果我错过了一个简单的步骤或类似的东西,我很抱歉...我试过这个?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);
  }'
)
Run Code Online (Sandbox Code Playgroud)

截至fibonacci(46)一切都很好,但后来我得到:

> fibonacci(47)
[1] -1323752223
> fibonacci(48)
[1] 512559680
> fibonacci(49)
[1] -811192543
> fibonacci(50)
[1] -298632863
Run Code Online (Sandbox Code Playgroud)

根据这个页面,上面应该是:

47 : 2971215073
48 : 4807526976
49 : 7778742049
50 : 12586269025
Run Code Online (Sandbox Code Playgroud)

你得到相同的结果吗?

Sim*_*lon 5

你超过了有符号整数的最大限制(从技术上讲,这是long int我猜的).使用double,而不是...

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
Run Code Online (Sandbox Code Playgroud)