简体   繁体   中英

Finding the value of infinite sums in r

I'm very new to r and programming so please stay with me:)

I am trying to use iterations to find the value of infinite iterations to the 4th decimal place. Ie where the 4th decimal does not change. so 1.4223, where 3 does not change anymore so the result to 3 decimal place is 1.422.

在此处输入图像描述

The link above shows an example of a similar problem that I am faced with. My question is how do I create a for-loop that goes to infinity and find the value where the 4th decimal point stops changing?

I have tried using while loops but I am not sure how to stop it from just looping forever. I need some if statement like below:

result <- 0
i <- 1
d <- 1e-4
while(TRUE)
{
    result <- result + (1/(i^2))
    if(abs(result) < d)
    {
        break
    }
    i <- i + 1

}
result

Here's an example: to do the infinite loop, use while(TRUE) {} , and as you suggested use an if clause and break to stop when necessary.

## example equation shown
## fun <- function(x,n) {
##     (x-1)^(2*n)/(n*(2*n-1))
## }
## do it for f(x)=1/x^2 instead
## doesn't have any x-dependence, but leave it in anyway
fun <- function(x,n) {
     1/n^2
}

n <- 1
## x <- 0.6
tol <- 1e-4
ans <- 0
while (TRUE) {
   next_term <- fun(x,n)
   ans <- ans + next_term
   if (abs(next_term)<tol) break
   n <- n+1
}

When run this gives ans=1.635082 , n=101 .

  • R also has a rarely used repeat { } keyword, but while(TRUE) will probably be clearer to readers
  • there are more efficient ways to do this (ie calculating the numerator by multiplying it by (x-1)^2 each time)
  • it's generally a good idea to test for a maximum number of iterations as well so that you don't set up a truly infinite loop if your series doesn't converge or if you have a bug in your code
  • I haven't solved your exact problem (chose a smaller value of tol ), but you should be able to adjust this to get an answer
  • as discussed in the answer to your previous question , this isn't guaranteed, but should generally be OK; you can check (I haven't) to be sure that the particular series you want to evaluate has well-behaved convergence

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM