Home > OS >  Writing a function for Ramanujan nested radicals
Writing a function for Ramanujan nested radicals

Time:11-18

I am writing a function for Ramanujan nested radicals in R. Ramanujan nested radicals equation is following: enter image description here

I need to take n as only input argument. I am not sure how to code it in R.

CodePudding user response:

I think this should do it

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

CodePudding user response:

Using recursion:

ram <- Vectorize(function(n, r = 1) ifelse(n <= 1, r, ram(n - 1, sqrt(1   n*r))))
ram(1:5)
[1] 1.000000 1.732051 2.236068 2.559830 2.755053

Reaches the limit of 3 with machine precision somewhere around 50-60:

3 - ram(seq(10, 100, 10))
[1] 1.007964e-02 1.211940e-05 1.317704e-08 1.382006e-11 1.421085e-14 0.000000e 00
[7] 0.000000e 00 0.000000e 00 0.000000e 00 0.000000e 00
  • Related