Is it possible to create a function for continued fraction estimation in R, given a vector of numerics?
The formula is:

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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With