作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我刚开始使用 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);
}'
)
fibonacci(46)
一切都很好,但后来我得到:
> fibonacci(47)
[1] -1323752223
> fibonacci(48)
[1] 512559680
> fibonacci(49)
[1] -811192543
> fibonacci(50)
[1] -298632863
47 : 2971215073
48 : 4807526976
49 : 7778742049
50 : 12586269025
最佳答案
您超出了 maximum limit对于有符号整数(从技术上讲,这将是 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
关于r - 使用 Rcpp 的斐波那契数列的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18877472/
我是一名优秀的程序员,十分优秀!