使用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