Unexpected result from fibonacci series using Rcpp

╄→гoц情女王★ 提交于 2019-12-10 15:42:37

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/18877472/unexpected-result-from-fibonacci-series-using-rcpp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!