gpt4 book ai didi

r - 使用 Rcpp 的斐波那契数列的意外结果

转载 作者:行者123 更新时间:2023-12-05 01:07:13 25 4
gpt4 key购买 nike

我刚开始使用 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

根据这个 page以上应该是:
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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com