Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R- continued fraction

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

The formula is:

enter image description here

like image 1000
tzema Avatar asked Oct 25 '25 04:10

tzema


1 Answers

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
like image 61
ThomasIsCoding Avatar answered Oct 26 '25 16:10

ThomasIsCoding