Is it possible to create a function for continued fraction estimation in R, given a vector of numerics?
The formula is:
CodePudding user response:
We can define a recursive function f
to calculate the contiuned fraction
f <- function(v) {
ifelse(length(v) == 1, v, v[1] 1 / f(v[-1]))
}
However, a drawback is that there is a limitation on the recursion depth, e.g.,
> f(1:1e5)
Error: node stack overflow
Thus, if you have a large array v
, a better option might be using for
loops, e.g.,
f <- function(v) {
if (length(v) == 1) {
return(v)
}
s <- tail(v, 1)
for (k in (length(v) - 1):1) {
s <- v[k] 1 / s
}
s
}
and you will see
> f(1:1e5)
[1] 1.433127
CodePudding user response:
Using recursion one option to achieve your desired result may look like so:
cfrac <- function(x) {
n <- length(x)
if (n > 1) {
res <- x[1] 1 / cfrac(x[2:n])
} else {
res <- x
}
return(res)
}
identical(cfrac(2), 2)
#> [1] TRUE
identical(cfrac(c(2, 3)), 2 1 / 3)
#> [1] TRUE
identical(cfrac(c(-3, 2, 18)), -3 1 / (2 1 / 18))
#> [1] TRUE