我认为这应该可以实现
RNR <- function(N) Reduce(function(n, x) sqrt(1 + n * x), 2:N, 1, right = TRUE)
sapply(2:10, RNR) #only valid for N>1
[1] 1.732051 2.236068 2.559830 2.755053 2.867103 2.929173 2.962723 2.980554 2.989920
使用递归进行矢量化:
ram <- function(n, r = rep(1, length(n))) {
i <- which(n > 1)
if (length(i)) r[i] <- Recall(n[i] - 1, sqrt(1 + n[i]*r[i]))
r
}
ram(1:5)
#> [1] 1.000000 1.732051 2.236068 2.559830 2.755053
机器精度达到极限 3
n = 57
:
which.max(ram(1:100) == 3)
#> [1] 57
针对已接受答案的基准:
microbenchmark::microbenchmark(
RNR = sapply(2:100, RNR),
ram = ram(2:100),
check = "equal"
)
#> Unit: microseconds
#> expr min lq mean median uq max neval
#> RNR 5874.801 6084.7515 6715.348 6193.950 6815.1510 11175.500 100
#> ram 659.101 737.1515 811.721 776.801 875.1505 1621.401 100