Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Rcpp的斐波那契级数的意外结果_R_Rcpp - Fatal编程技术网

使用Rcpp的斐波那契级数的意外结果

使用Rcpp的斐波那契级数的意外结果,r,rcpp,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)) + f

我刚刚开始使用
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);
  }'
)
根据这一点,上述内容应为:

47 : 2971215073
48 : 4807526976
49 : 7778742049
50 : 12586269025
你得到了相同的结果吗?

你超过了有符号整数的极限(从技术上讲,我想这将是一个
长整数)。改用
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
库(Rcpp)
sourceCpp(代码=)
#包括
//[[Rcpp::导出]]
双斐波那契(常数双x){
如果(x==0)返回(0);
如果(x==1)返回(1);
收益率(斐波那契(x-1))+斐波那契(x-2);
}'
)
斐波那契(47)
#[1] 2971215073

Oh。。好啊实际上,我将
int
替换为
long
,它给出了相同的数字。。。但是我没有想到双倍我觉得时间足够了。。。无论如何谢谢你
int
long
的大小相同。但即使使用了更大的整数类型,R的整数类型本身也只有这么大。@Peyton好的,谢谢,我以为int是16位32长的。。。我的错!谢谢你们。@Michele,这取决于:注意:R只有
int
double
类型。如果您需要整数的额外精度,则必须使用
double
,除非您使用附加包(eg)+1作为一个自包含的可复制示例。非常好。@SimonO101感谢+1(始终接受),但老实说,我只是从
?sourceCpp
复制并粘贴了它。即使我自己可能已经完成了斐波那契函数,但在C:-(同样,你不需要
#include
,它是由
sourceCpp()添加的(连同其他支架)
@DirkEddelbuettel哦,我明白了,谢谢。就像我说的,我昨天就开始了,所以现在我只是按照文档(和你们研讨会上的代码)的原样来做,即使这样做了,其中一些文档也没有编译…问题来了…为了完整性:
cppFunction('double fib(double x){if(x)}
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